子线程10次,然后主线程100次,然后子线程10次,然后主线程100次。循环50次
package cn.itcast.heima2; public class TraditionalThreadComunication { public static void main(String[] args) { // TODO Auto-generated method stub Business business = new TraditionalThreadComunication().new Business(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 50; i++) { business.sub(i); } } }).start(); for (int i = 0; i < 50; i++) { business.main(i); } } class Business { private boolean bShouldSub=true; public synchronized void sub(int i) { if(!bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int j = 0; j < 10; j++) { System.out.println("sub thread sequence:" + j + " loop of " + i); } bShouldSub=false; this.notify(); } public synchronized void main(int i) { if(bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int j = 0; j < 100; j++) { System.out.println("main thread sequence:" + j + " loop of " + i); } bShouldSub=true; this.notify(); } } }
时间: 2024-12-18 19:34:08