4-使用synchronized实现线程间通信-实现线程间通信方式(1)

来源:互联网 发布:mysql存储图片 编辑:程序博客网 时间:2024/06/02 02:57

一、主要内容

实现子线程运行10次,主线程运行100次,子线程、主线程交替进行,此过程循环进行50次。

二、代码实现

package cn.yjx.thread;public class TraditionalThreadCommunication {public static void main(String[] args) {final Business business = new Business();// 子线程new Thread(new Runnable() {@Overridepublic void run() {for(int i=1;i<=50;i++){business.sub(i);}}}).start();// 主线程for(int i=1;i<=50;i++){business.main(i);}}}  class Business {  private boolean bShouldSub = true; // 线程间进行通信的变量  // 子  public synchronized void sub(int i){  while(!bShouldSub){  try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}  }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 blocke.printStackTrace();}  }for(int j=1;j<=100;j++){System.out.println("main thread sequence of " + j + ",loop of " + i);}bShouldSub = true;this.notify();  }  }

0 0
原创粉丝点击