【问题标题】:Sequential execution of threads freezes线程的顺序执行冻结
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多