java线程通信复习

public class TraditionalThreadCommunication {

 /**
  * @param args
  * 这个例子可以理解java的通信机制
  * 题目是子线程运行10次,主线程运行100次,然后重复50次
  * 遇到这种需求的题目,一般要把结构想清楚,最好把做的同样的事放在一个类
  * 机构里面来管理,方便同步和通信
  */
 public static void main(String[] args) {
  
  final Business business = new Business();
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       //子线程运行10次 总共50次
       business.sub(i);
      }
      
     }
    }
  ).start();
  // 主线程运行100次,然后重复50次
  for(int i=1;i<=50;i++){
   business.main(i);
  }
  
 }

}
// 核心通信类
  class Business {
// 用来控制通信与互斥的变量
   private boolean bShouldSub = true;
//   首先synchronized同步只是保证了执行十次里面的逻辑可以同步,但是
//   并不能保证线程之间来回的同步,所以,除了加synchronized外,还必须
//   试用线程等待和激活机制来控制
   public synchronized void sub(int i){
    while(!bShouldSub){
     try {
    // 线程等待
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
    }
    // 执行10次
   for(int j=1;j<=10;j++){
    System.out.println("sub thread sequence of " + j + ",loop of " + i);
   }
//  将变量回置,方便主线程执行
    bShouldSub = false;
//    激活主线程
    this.notify();
   }
  
   public synchronized void main(int i){
     while(bShouldSub){
      try {
     this.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
     }
   for(int j=1;j<=100;j++){
    System.out.println("main thread sequence of " + j + ",loop of " + i);
   }
   bShouldSub = true;
   this.notify();
   }
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值