无法正确解释等待并通知程序

时间:2013-09-02 17:35:51

标签: java synchronization wait

当我尝试运行以下代码时,代码不会进入带有wait()的块或带有notifyAll()的块。但是,程序的结果是“A B”或“B A”。我不明白我在节目中遗漏了什么。

public class threads1 extends Thread {

    static Object obj = new Object();

    public threads1(String str) {
        super(str);
    }

    public void run() {
        try {
            waitforsignal();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void waitforsignal() throws InterruptedException {

        synchronized (obj) {
            System.out.println(Thread.currentThread().getName());
            while (Thread.currentThread().getName() == "A") {
                System.out.println("into wait");
                obj.wait();
            }
            if ((Thread.currentThread().getName() == "B")) {
                System.out.println("had notified");
                obj.notifyAll();
            }
        }
    }

    public static void main(String... strings) throws InterruptedException {
        Thread t1 = new threads1("A");
        Thread t2 = new threads1("B");
        t1.start();
        t2.start();
    }
}

1 个答案:

答案 0 :(得分:1)

它与线程无关:you are comparing strings with == instead of equals

修复后,请注意线程t1

Thread.currentThread().getName().equals("A")

永远是真的,所以你的程序永远不会完成......