- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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
对这里有帮助吗?
非常感谢!
最佳答案
你可以使用Thread
的UncaughtExceptionHandler
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/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!