java - 如何停止ExecutorService中的其他线程?
问题描述
我制作了一个客户端-服务器聊天应用程序,但线程不平衡,因为我只能终止池中的一个线程(2 个线程)。
例如,服务器启动。它创建一个带有两个线程的池(一个用于发送,一个用于接收)。服务器发送一条消息。它删除用于发送的原始线程并创建一个新池。现在有原来的接收线程和一个新的池,还有两个线程。相反的故事(接收消息)也是如此。
两个线程都在等待输入或输出,所以我认为我无法检查其他线程是否在池中完成。
代码是这样的
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<String> send = executorService.submit(this::send);
Future<String> receive = executorService.submit(this::receive);
<some code to check to see if the future is completed>
sendComplete.cancel(true);
receiveComplete.cancel(true);
executorService.shutdownNow();
private void send() throws IOException {
OutputStream os= socket.getOutputStream();
BufferedReader read= new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw= new PrintWriter(os, true);
********String msg= read.readLine(); //This is wear it freezes
pw.println(messageOutput);
pw.flush();
}
由于类似的线路,接收冻结。
有没有办法终止/关闭 ExecutorService/池中的所有线程?shutdownNow() 不起作用,因为线程中的代码被冻结/卡在等待输入/输出。
解决方案
推荐阅读
- reactjs - 即使 src 失败,也显示图像的替代文本
- python - 在“单元格”中搜索关键字时出现熊猫键错误
- botframework - 自适应卡片后退按钮
- automated-tests - 有没有办法在 Postman 测试中检查 JSON 响应的结构?
- php - 如何将图像文件从 PC(本地主机)上传到 PHP 中位于服务器(例如 godaddy.com)上的目录?
- azure - 如何在 Visual Studio 数据库项目中管理 SQL Server Always Encrypted Keys 架构
- python - Pandas 持续时间 groupby - 以定义的值开始组范围
- f# - 哪些 F# 类型名称和声明语法被认为是惯用的?
- mysql - 如何更改 Laravel 项目的 MySQL DB UTC 时间?
- highcharts - 需要使用堆叠和分组的柱形图进行深入研究