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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘海源 中级黑马   /  2012-7-24 23:09  /  991 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次
public class ThreadTest {
   
     public static void main(String[] args) {
         
          new ThreadTest().init();
     }
     public void init()
     {
          final Business business = new Business();
          new Thread(
                   new Runnable()
                   {
                        public void run() {
                             for(int i=0;i<50;i++)
                             {
                                  business.SubThread(i);
                             }                           
                        }
                        
                   }
         
          ).start();
         
          for(int i=0;i<50;i++)
          {
              business.MainThread(i);
          }         
     }
     
     private class Business
     {
          boolean bShouldSub = true;//这里相当于定义了控制该谁执行的一个信号灯
          public synchronized void MainThread(int i)
          {
              if(bShouldSub)
                   try {
                        this.wait();
                   } catch (InterruptedException e) {
                        
                        e.printStackTrace();
                   }         
                  
              for(int j=0;j<5;j++)
              {
                   System.out.println(Thread.currentThread().getName() + ":i=" + i +",j=" + j);
              }
              bShouldSub = true;
              this.notify();
         
          }
         
         
          public synchronized void SubThread(int i)
          {
              if(!bShouldSub)
                   try {
                        this.wait();
                   } catch (InterruptedException e) {
                     
                        e.printStackTrace();
                   }   
                  
              for(int j=0;j<10;j++)
              {
                   System.out.println(Thread.currentThread().getName() + ":i=" + i +",j=" + j);
              }
              bShouldSub = false;               
              this.notify();         
          }
     }
}
如果不在用synchronized的话,那还可以怎么写,我这个个人觉得效率不高,希望大家可以给我出个好主意???

评分

参与人数 1技术分 +1 收起 理由
韦念欣 + 1 赞一个!

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马