此代码:
import java.util.*;
import static java.lang.System.out;
public class Main {
public static void main(String[] args) {
Test t = new Test();
My1 m1 = new My1(t);
My2 m2 = new My2(t);
}
}
class Test {
enum State {
one, two, three
}
int i;
volatile State state = State.one;
synchronized void one() {
while(state != State.one)
try {
wait();
} catch(InterruptedException e) {}
i++;
out.println("One: "+i);
state = State.two;
notify();
}
synchronized void two() {
while(state != State.two)
try {
wait();
} catch(InterruptedException e) {}
i++;
out.println("Two: "+i);
state = State.three;
notify();
}
synchronized void three() {
while(state != State.three)
try {
wait();
} catch(InterruptedException e) {}
i++;
out.println("Three: "+i);
state = State.one;
notify();
}
}
class My1 implements Runnable {
Thread t;
Test test;
My1(Test tst) {
test = tst;
t = new Thread(this, "My1");
t.start();
}
public void run() {
out.println(t);
while(true)
test.one();
}
}
class My2 implements Runnable {
Thread t;
Test test;
My2(Test tst) {
test = tst;
t = new Thread(this, "My2");
t.start();
}
public void run() {
out.println(t);
while(true)
test.two();
}
}
class My3 implements Runnable {
Thread t;
Test test;
My3(Test tst) {
test = tst;
t = new Thread(this, "My3");
t.start();
}
public void run() {
out.println(t);
while(true)
test.three();
}
}
它不能按我的需要工作。启动后,将显示“一”和“二”,并且程序将冻结。我使用了volatile,它并没有帮助我。请帮助解决它并使此代码正常工作。 (我看到了类似的答案,但它们并不适合我,我需要在不重构的情况下使此代码正常工作)
答案 0 :(得分:0)
我相信您永远不会进行notify()
方法调用,因为在每个方法调用之前都有一个wait()
调用。 wait()
调用将永远不允许调用notify()
方法。
以下是对当调用wait()方法时发生的情况的恰当解释:Difference Between Wait and Sleep in Java