一个线程通信问题(sub运行10次,然后main运行100次,这样交替循环50次)

来源:互联网 发布:网络禁区相似的动漫 编辑:程序博客网 时间:2024/05/04 16:37
  1. /** 
  2.  * sub运行10次,然后main运行100次,这样交替循环50次 
  3.  * @author Administrator 
  4.  * 
  5.  */  
  6. public class TraditionalThreadCommunication {  
  7.   
  8.     /** 
  9.      * @param args 
  10.      */  
  11.     public static void main(String[] args) {  
  12.           
  13.         final Business business = new Business();  
  14.         new Thread(  
  15.                 new Runnable() {              
  16.                     @Override  
  17.                     public void run() {  
  18.                         for(int i=1;i<=50;i++){  
  19.                             business.sub(i);  
  20.                         }     
  21.                     }  
  22.                 }  
  23.         ).start();  
  24.           
  25.           
  26.         new Thread(new Runnable() {  
  27.               
  28.             @Override  
  29.             public void run() {  
  30.                 for(int i=1;i<=50;i++){  
  31.                     business.main(i);  
  32.                 }     
  33.             }  
  34.         }).start();  
  35.           
  36.     }  
  37.   
  38. }  
  39.   class Business {  
  40.       private boolean bShouldSub = true;  
  41.       public synchronized void sub(int i){  
  42.           while(!bShouldSub){  
  43.               try {  
  44.                 this.wait();  
  45.             } catch (InterruptedException e) {  
  46.                 // TODO Auto-generated catch block  
  47.                 e.printStackTrace();  
  48.             }  
  49.           }  
  50.             for(int j=1;j<=10;j++){  
  51.                 System.out.println("sub thread sequence of " + j + ",loop of " + i);  
  52.             }  
  53.           bShouldSub = false;  
  54.           this.notify();  
  55.       }  
  56.         
  57.       public synchronized void main(int i){  
  58.             while(bShouldSub){  
  59.                 try {  
  60.                     this.wait();  
  61.                 } catch (InterruptedException e) {  
  62.                     // TODO Auto-generated catch block  
  63.                     e.printStackTrace();  
  64.                 }  
  65.             }  
  66.             for(int j=1;j<=100;j++){  
  67.                 System.out.println("main thread sequence of " + j + ",loop of " + i);  
  68.             }  
  69.             bShouldSub = true;  
  70.             this.notify();  
  71.       }  
  72.   }  

0 0
原创粉丝点击