线程学习---对synchronized的测试

public class myThread extends Thread {
 public void run() {
  synchronized(System.out){
   for (int i = 0; i < 10; i++) {
    try{
     sleep(100);
    }catch(InterruptedException e){e.printStackTrace();}
    
    System.out.println(getName() + ": i=" + i);
    if (i==9) System.out.println("=========");
   }
  }
 }

 public static void main(String[] a) {
  myThread thread1 = new myThread();
  myThread thread2 = new myThread();
  thread1.setName("A");thread1.start();
  thread2.setName("B");thread2.start();
 }
}

在这个测试中,由于执行所需时间片太短,如果不在其中加一句sleep(100)的话,线程A 和线程B的交叉就体现不出来,就更不用说验证synchronized的作用了; 另,注意synchronized所同步的对象是System.out, 而不是this.

posted on 2007-05-22 09:34 心砚 阅读(237) 评论(0)  编辑  收藏 所属分类: Java


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(2)

随笔分类

文章分类

文章档案

Forum

搜索

最新评论

阅读排行榜

评论排行榜