首页 > 解决方案 > 如何停止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() 不起作用,因为线程中的代码被冻结/卡在等待输入/输出。

标签: javamultithreadingserverclientexecutorservice

解决方案


推荐阅读