• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
开水房
ASP.NET
博客园    首页    新随笔    联系   管理    订阅  订阅
java 多线程 资源共享
在控制资源共享的语句外,加入 synchronized(this)  (this也可用private Object o 对象),来进行写锁保护 

 

 

class M
{
private static M m = new M();
public static M getInstance()
{
return m;
}
public void check(int i)
{
System.out.println("I'm waiting, Thread "+i);
synchronized(this)
{
System.out.println("I'm processing, Thread "+i);
try {
Thread.sleep(5000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
synchronized void method(int i)
{
System.out.println("I'm in synchronized function "+ i);
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class CheckCloneable implements Runnable
{
private int i;
private boolean test_function_syn;
CheckCloneable(int i,boolean test_function_syn)
{
this.i = i;
this.test_function_syn = test_function_syn;
}
public void run()
{
M m = M.getInstance();
if(!test_function_syn)
{
m.check(i);
}
else
{
System.out.println("I'm waiting synchronized function "+ i);
m.method(i);
}
}
public static void main(String[] args)
{
for(int i=0;i<5;i++)
{
System.out.println("main");
CheckCloneable c = new CheckCloneable(i,true);
Thread t = new Thread(c);
t.start();
}
}
}

 

posted on 2010-08-16 09:44  白开水皮皮  阅读(367)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3