传统wait()和notify()通信技术 发表于 2018-02-22 | 分类于 juc 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566package cn.itcast.heima2;public class TraditionalThreadCommunication { /** * 子线程10次,主线程100次,交替执行50次 * @param args */ public static void main(String[] args) { final Business business = new Business();//todo 共享实例 new Thread( new Runnable() { @Override public 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;//todo 共享变量 public synchronized void sub(int i){//synchronized 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){//synchronized 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(); } }