[英]Problem with cleaning up a thread pool
我在 Java 中有一个服务器,它是多线程的,我已经为它创建了一个线程池。 现在一切顺利,我的服务器接受并从连接到它的客户端读取数据,但我真的不知道在连接关闭后如何清理 sockets。
所以这是我的代码:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ThreadPooledServer server = new ThreadPooledServer(queue,7001);
new Thread(server).start();
}
ThreadPooledServer class:
public class ThreadPooledServer implements Runnable {
protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
public ThreadPooledServer(BlockingQueue queue,int port) {
this.serverPort = port;
this.queue=queue;
}
public void run() {
openServerSocket();
while (!isStopped()) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
clientconnection++;
} catch (IOException e) {
if (isStopped()) {
System.out.println("Server Stopped.");
return;
}
throw new RuntimeException("Error accepting client connection", e);
}
WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);
this.threadPool.execute(workerRunnable);
}
this.threadPool.shutdown();
System.out.println("Server Stopped.");
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
}
catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
这是我不明白的:我的while()
循环接受客户端的工作时间与isStopped
一样长是假的。
当isStopped
设置为 true 时,我的循环结束,然后我关闭了我的线程池,这是正确的。
isStopped 在 onstop(){.................................}.... 中设置为 true
我应该在哪里调用 onstop()...?
因为此时我没有使用这个方法,我没有调用它,这意味着我没有正确清理我的线程。
WorkerRunnable class:
public class WorkerRunnable implements Runnable {
public WorkerRunnable(BlockingQueue queue2, Socket clientSocket2) {
// TODO Auto-generated constructor stub
this.clientSocket2 = clientSocket2;
this.queue2 = queue2;
}
public void run() {
try {
is = new ObjectInputStream(this.clientSocket2.getInputStream());
try {
while (!stop) {
System.out.println("Suntem in interiorul buclei while:!");
v = (Coordinate) is.readObject();
queue2.put(v);
}
} catch (Exception e) {
e.printStackTrace();
is.close();
clientSocket2.close();
}
is.close();
clientSocket2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
this.stop = true;
}
}
}
在这里我有同样的问题。 我应该如何正确清理和关闭 sockets?
一旦你调用了shutdown()
,一旦所有任务完成,线程池就会关闭每个线程。
您应该从知道池应该关闭的任何代码中调用onstop()
。 这取决于您的应用程序的 rest 做了什么,以及为什么要在应用程序完成之前停止池。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.