有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

当我尝试运行下面的代码时,代码既不会进入wait()块,也不会进入notifyAll()块。然而,该计划的结果是“AB”或“BA”。我不明白我在节目中遗漏了什么

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) 个答案