①子线程执行十次 ② 然后主线程执行五十次 ③ 一二两过程循环20次
package com.tb.Test;
public class TraditionalThreadCommunication {
public static void main(String[] args) {
TraditionalThreadCommunication.init();
}
private static void init() {
Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<=20;i++){
business.sub(i);
}
}
}).start();
for(int i=1;i<=20;i++){
business.main(i);
}
}
static class Business{
private boolean flag= true;
private synchronized void sub(int i){
while(!flag){ //防止伪唤醒
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread sequece of "+j+" loop of"+i);
}
flag= false;
this.notify();
}
private synchronized void main(int i){
while(flag){ //防止伪唤醒
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=50;j++){
System.out.println("main thread sequece of "+j+" loop of"+i);
}
flag= true;
this.notify();
}
}
}