本帖最后由 崔朋朋 于 2012-9-21 17:39 编辑
//子线程循环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();
}
for (int j = 1; j <= 5; j++) {
System.out.println("sub: " + j + " loop: " + i);
}
bShouldSub = false;
this.notify();
}
public synchronized void main(int i) throws Exception {
//若是子线程,则主线程wait
while (bShouldSub) {
this.wait();
}
for (int j = 1; j <= 10; j++) {
System.out.println("main: " + j + " loop: " + i);
}
bShouldSub = true;
this.notify();
}
}
我的问题是:
两个线程谁先执行不一定,但如果先执行子线程的business.sub(i);则执行到this.notify();发现没有线程wait,则应该报异常。
但多次反复执行,都没有报异常报出,是在怎么回事?
|