Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法正确解释等待和通知程序_Java_Synchronization_Wait - Fatal编程技术网

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

Java 无法正确解释等待和通知程序,java,synchronization,wait,Java,Synchronization,Wait,当我尝试运行下面的代码时,代码既不会进入wait()块,也不会进入notifyAll()块。然而,该计划的结果是“AB”或“BA”。我不明白我在节目中遗漏了什么 public class threads1 extends Thread { static Object obj = new Object(); public threads1(String str) { super(str); } public void run() {

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

它与线程无关:

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

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

将始终为true,因此您的程序将永远不会完成…

并且不是Thread。currentThread().getName()将生成一个字符串。由于从不同引用创建的字符串对象最终总是指向池中的同一个字符串引用,为什么==不能使用?这里所有的字符串都是编译时常量,因此由于字符串的内部处理,我认为这不是问题所在。@TedHopp,我不确定您是否可以在不知道
线程
的impl的情况下做出这样的假设。实际上,在这里,线程名被转换成一个字符数组,然后返回到
getName()
@TedHopp的字符串,除了当使用
new Thread
调用线程时,该线程不存储字符串本身,而是在调用
getName
时创建一个
char[]
和一个新字符串。将“while”关键字更改为“if”。现在这个程序正如我所期望的那样工作。