线程同步通信

来源:互联网 发布:网站视频分段播放 php 编辑:程序博客网 时间:2024/05/22 00:50

package itcast.thread;

/*
 *
 */
public class TraditionalThreadCommunication {

 public static void main(String[] args) {
  TraditionalThreadCommunication t = new TraditionalThreadCommunication();
  final Business b = t.new Business();
  new Thread(new Runnable() {
   public void run() {
    for(int i=1;i<=50;i++){
     b.sub(i);
    }
   }
  }).start();
  for(int i=1;i<=50;i++){
   b.main(i);
  }
 }
 public class Business{
  private boolean shouldSub = true;
  public synchronized void sub(int n){
   while(!shouldSub){
    try {
     this.wait();//用同步监视器对象 this
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   for(int i=1;i<=10;i++){
    System.out.println("sub thread sequence of " + i + ", loop of " + n);
   }
   shouldSub = false;
   this.notify();
  }
  public synchronized void main(int n){
   while(shouldSub){
    try {
     this.wait();//一定要用同步监视器对象 this
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   for(int i=1;i<=100;i++){
    System.out.println("main thread sequence of " + i +", loop of "+ n);
   }
   shouldSub = true;
   notify();
  }
 }
}

原创粉丝点击