A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© dangfei 中级黑马   /  2012-2-23 09:35  /  2335 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public static void main(String[] args) {
                // TODO Auto-generated method stub
            new testThread("线程1").start();
            new testThread("线程2").start();
            new testThread("线程3").start();
        }

}

class  testThread extends Thread{
        public synchronized  void run() {
                //notify();
                int a=0;
                try {
                        while(a<8)
                        {
                            
                                //notifyAll();
                                System.out.println(getName()+"|"+a);
                                sleep(1000);
                                a++;
                                for(int i=1;i<=10;i++)
                                        System.out.println(getName()+"|!"+i);
                        }
                       
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }               
        }
        public testThread(String name)
        {
                super(name);
        }

synchronized保证方法在同一时间只有一个线程执行,但上面代码结果中,for循环输出结果为什么不连续。
猜想原因可能是sleep(1000);。但是如果在synchronized内部用sleep(),线程睡醒后就不管synchronized了,sleep()岂不是破坏了synchronized。

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

2 个回复

倒序浏览
  1. class  testThread extends Thread{

  2.         public void run() {
  3.                 synchronized(testThread.class) //修改为同步下面的代码。我好像没见过同步run()方法的做法,呵呵,还有待研究
  4.                 {
  5.                 //notify();
  6.                 int a=0;
  7.                 try {
  8.                         while(a<8)
  9.                         {
  10.                            
  11.                                 //notifyAll();
  12.                                 System.out.println(getName()+"|"+a);
  13.                                 sleep(1000);
  14.                                 a++;
  15.                                 for(int i=1;i<=10;i++)
  16.                                         System.out.println(getName()+"|!"+i);
  17.                         }
  18.                         
  19.                 } catch (Exception e) {
  20.                         // TODO Auto-generated catch block
  21.                         e.printStackTrace();
  22.                 }      
  23.               }         
  24.         }
  25.         public testThread(String name)
  26.         {
  27.                 super(name);
  28.         }

  29. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
同步函数的锁是this,三个线程就拥有三个各自的this,所以楼主的代码并没有实现同步,当然打印结果不能连续输出。这个时候使用代码块,将锁设为testThread.class或者主函数的class即可,总之要保证锁的唯一性。

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马