//子线程循环5次,主线程循环10次,接着又到子线程循环5次,接着又到主线程循环10次,如此反复50次
public class TraditionalThreadComunication {
public static void main(String[] args){
final Business business = new Business();
// 子线程
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
try {
business.sub(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
// 主线程
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
try {
business.main(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
class Business {
// sub与main已经互斥了
private boolean bShouldSub = true;
public synchronized void sub(int i) throws Exception {
//若不是子线程,则子线程wait
while (!bShouldSub) {
this.wait();
}