【发布时间】:2020-01-18 16:28:22
【问题描述】:
这段代码:
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,但对我没有帮助。请帮助解决它并使此代码正常工作。 (我看了类似的答案,但它们不适合我,我需要让这段代码在不重构的情况下工作)
【问题讨论】:
-
使用
noitfyAll()。如果只使用notify(),则无法确定线程 3 是否应该唤醒。 -
你在哪里创建
My3? -
Johannes Kuhn,这里我忘了在代码中包含它,但同样的挂起发生了
-
当你用
notifyAll()替换所有notify()调用时?
标签: java multithreading volatile