gpt4 book ai didi

java - 线程的顺序执行卡住

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:53 29 4
gpt4 key购买 nike

这段代码:

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 的,它对我没有帮助。请帮助解决这个问题并使该代码正常工作。(我看过类似的答案,但它们不适合我,我需要让这段代码正常工作而不重构它)

最佳答案

我相信您永远不会调用 notify() 方法,因为在每个方法调用之前都有一个 wait() 调用。 wait() 调用永远不会允许调用 notify() 方法。

下面是对调用 wait() 方法时发生的情况的一个很好的解释:Difference Between Wait and Sleep in Java

关于java - 线程的顺序执行卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980489/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com