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

© liumeng 中级黑马   /  2012-3-23 07:51  /  1310 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class TestThread1 {

        /**
         * @param args
         */
        public static void main(String[] args) {
                final printChar business = new printChar();
                new Thread(
                                new Runnable() {
                                       
                                        @Override
                                        public void run() {
                                       
                                                for(int i=1;i<=20;i++){
                                                        business.sub1(i);
                                                }
                                                
                                        }
                                }
                ).start();
                try {
                                        Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                for(int i=1;i<=20;i++){
                        business.sub2(i);
                }

        }

}

class printChar {
          private boolean bShouldSub1 = true;

          public synchronized void sub1(int i){
                  while(!bShouldSub1){
                          try {
                                this.wait();
                        } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                  }
                for(int j=1;j<=2;j++){
                        System.out.print("a");
                }
                  bShouldSub1 = false;
                  this.notify();
          }

          public synchronized void sub2(int i){
                          while(bShouldSub1){
                                  try {
                                        this.wait();
                                } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                          }
                        
                        System.out.print("b");
                        
                        bShouldSub1 = true;
                        this.notify();
          }
}
如果调用notify 但没有wait的线程怎么不会出错了

2 个回复

倒序浏览
是不是只有调用WAIT方法时才会调用notify呢
回复 使用道具 举报
notify方法,是唤醒线程池中的第一个等待线程,如果没有线程,对程序运行没影响,所以是多余,不是错误;
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马