gpt4 book ai didi

java - 为什么 b.wait() 不让主线程等待

转载 作者:行者123 更新时间:2023-12-01 06:22:04 25 4
gpt4 key购买 nike

不知道为什么 b.wait() 不等待主线程。如果我们创建一个虚拟对象,则 Object a = new Object();它等待着。如果我用 Thread 扩展 ThreadA 并为 ThreadA 创建一个实例并使用 ThreadA 引用进行锁定,它就可以工作。但为什么下面的 wait() 不起作用

package com.aircell;

public class ThreadA{
public static void main(String[] args){
ThreadB b = new ThreadB();
b.start();
System.out.println("who is this thread");
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}

System.out.println("Total is: " + b.total);
}
}
}

class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;

}

}
System.out.println("done thread");
}
}

最佳答案

首先:如果我在这里尝试你的类(class)[TM],我会得到以下输出:

who is this thread
Waiting for b to complete...
done thread
Total is: 4950

所以它确实有效,这有点令人惊讶,但我认为 wait 的 Javadoc 中的以下句子似乎发生在这里:

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop.

以下更改应该为您提供您想要实现的行为:

public class ThreadA{
public static void main(String[] args){
ThreadB b = new ThreadB();
System.out.println("who is this thread");
synchronized(b){
b.start();
try{
System.out.println("Waiting for b to complete...");
while (!b.finished) {
b.wait();
}
}catch(InterruptedException e){
e.printStackTrace();
}

System.out.println("Total is: " + b.total);
}
}
}

class ThreadB extends Thread{
int total;
boolean finished;
@Override
public void run(){
synchronized(this){
try {
for(int i=0; i<100 ; i++){
total += i;
}
}
finally {
finished = true;
this.notifyAll();
}
}
System.out.println("done thread");
}
}

关于java - 为什么 b.wait() 不让主线程等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com