0

当我尝试运行以下代码时,代码既不会进入带有 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();
    }
}
4

1 回答 1

1

它与线程无关:您将字符串与==而不是equals.

一旦你解决了这个问题,请注意线程t1

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

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

于 2013-09-02T17:43:12.673 回答