繁体   English   中英

线程的顺序执行冻结

[英]Sequential execution of threads freezes

这段代码:

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()方法时正在发生的事情的恰当解释: Java中Wait和Sleep之间的区别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM