gpt4 book ai didi

java - 向主线程发送线程错误信号

转载 作者:行者123 更新时间:2023-11-29 09:28:07 28 4
gpt4 key购买 nike

我在 Java 中有一个线程连接到套接字并将信息发送到另一个正在处理该信息的线程。

现在,如果“生产者”线程因任何原因失败,我希望整个程序停止,因此必须发生某种通知。

这是我的程序(非常简化):

public class Main {
private Queue<String> q = new ConcurrentLinkedQueue();

public static void main(String[] args) throws IOException {
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();

// Catch any error in the producer side, then stop both consumer and producer, and do some extra work to notify me that there's an error...
}
}

主要代码只是创建一个共享队列,并启动生产者和消费者。到目前为止,我想这还好吗?现在Producer代码是这样的:

public class Producer implements Runnable {
private Queue<String> q;

public Producer(Queue<String> q) {
this.q = q;
}

public void run() {
try {
connectToSocket();
while(true) {
String data = readFromSocket()
q.offer(data);
}
} catch (Exception e) {
// Something really bad happened, notify the parent thread so he stops the program...
}
}
}

生产者连接到套接字,读取并发送到队列中的字符串数据... 消费者:

public class Consumer implements Runnable {
private Queue<String> q;

public Consumer(Queue<String> q) {
this.q = q;
}

public void run() {
while(true) {
String dataFromSocket = q.poll();
saveData(dataFromSocket);
}
}
}

我的代码所做的远不止于此,但我认为现在我想做的事情已经不言自明了。我读过 wait()notify() 但我认为那行不通,因为我不想等待我的线程出现异常,我想以更好的方式处理它。有哪些替代方案?

总的来说,我的代码看起来合理吗?使用 ExecutorService 对这里有帮助吗?

非常感谢!

最佳答案

你可以使用ThreadUncaughtExceptionHandler

Thread.setDefaultExceptionHandler(
new UncaughtExceptionHandler() {
public void unchaughtException(Thread th, Throwable exception) {
System.out.println("Exception from Thread" + th + ". Exception:" + exception);
}
});

Java 文档 http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.UncaughtExceptionHandler.html

关于java - 向主线程发送线程错误信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963023/

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