【发布时间】:2013-09-03 14:37:03
【问题描述】:
我已经尝试过这段代码。但是在打印 0 之后,它什么也不打印。 我认为它是由于某些锁定而阻塞的。
public class EvenOdd implements Runnable {
private Object o = new Object();
private volatile int i = 0;
public void run() {
try {
System.out.println();
if ( Thread.currentThread().getName().equals( "Even")) {
printEven();
} else {
printOdd();
}
} catch ( Exception ee) {
ee.printStackTrace();
}
}
private void printEven() throws InterruptedException {
while ( true) {
synchronized ( o) {
while ( this.i % 2 == 0) {
o.wait();
}
System.out.println( Thread.currentThread().getName() + i);
i++;
o.notify();
}
}
}
private void printOdd() throws InterruptedException {
while ( true) {
synchronized ( o) {
while ( this.i % 2 != 0) {
o.wait();
}
System.out.println( Thread.currentThread().getName() + i);
i++;
o.notify();
}
}
}
}
我的测试类:
EvenOdd x = new EvenOdd();
new Thread(x,"Even").start();
new Thread(x,"Odd").start();
我哪里错了? 谢谢。
P.S : 我知道这种问题已经被问过很多次了,但我想自己尝试一下。
【问题讨论】:
标签: java multithreading locking synchronized runnable