子线程循环10次,接着主线程循环100次,接着回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
package com.jb.liang; public class TraditionalThread3 { /** * 互斥,上锁都是放在待操作的资源的类的内部方法中,而不是线程代码中 * @author jiall * 子线程循环10次,接着主线程循环100次,接着回到子线程循环10次,接着再回到主线程循环100次,如此循环50次 * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub final Busness busness=new Busness(); Thread thread=new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <=50; i++) { busness.sub(i); } } }); thread.start(); for (int i = 1; i <=50; i++) { busness.main(i); } } } //资源对象内部类 class Busness{ private boolean bShouldSub=true; public synchronized void sub(int i) { while (!bShouldSub) { try { this.wait();//wait } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <=10; j++) { System.out.println("sub:"+i+".."+j); } bShouldSub=false; this.notify();//取消wait } public synchronized void main(int i) { while (bShouldSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <=100; j++) { System.out.println("main:"+i+".."+j); } bShouldSub=true; this.notify(); } }