gpt4 book ai didi

java - 如何告诉主线程部分线程工作已完成

转载 作者:行者123 更新时间:2023-12-01 14:17:40 25 4
gpt4 key购买 nike

notify 真的只有在线程结束后才起作用吗?在下面的代码中,在我发表评论(true)之前我无法收到通知。如何告诉主线程部分线程工作已完成?

public class ThreadMain {
public Thread reader;
private class SerialReader implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(3000);
synchronized(this) {
System.out.println("notifying");
notify();
System.out.println("notifying done");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}

ThreadMain() {
reader = new Thread(new SerialReader());
}

public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
synchronized(d.reader) {
try {
d.reader.wait();
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
}

最佳答案

您应该尽量避免在较新版本的 Java 中使用 waitnotify,因为它们很难正确执行。尝试使用类似 BlockingQueue 的东西来代替

public class ThreadMain {
public final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<>();
private class SerialReader implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(3000);
System.out.println("notifying");
queue.offer(Boolean.TRUE);
System.out.println("notifying done");
} catch (Exception e) {
System.out.println(e);
}
}
}
}

ThreadMain() {
reader = new Thread(new SerialReader());
}

public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
try {
d.queue.take(); // block until something is put in the queue
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}

关于java - 如何告诉主线程部分线程工作已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17974123/

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