我有以下逻辑(简化):
public class Application {
public static volatile boolean stopServer;
private static ScheduledExecutorService taskScheduler;
private static Thread listenerThread;
public static synchronized void switchStopServer() {
stopServer = true;
listenerThread.interrupt();
taskScheduler.shutdownNow();
}
public static void main(String[] args) {
int threadPoolSize = 4;
taskScheduler = Executors.newScheduledThreadPool(threadPoolSize);
listenerThread = new ListenerThread();
taskScheduler.schedule(listenerThread, 0, TimeUnit.NANOSECONDS);
}
}
public class ListenerThread extends Thread {
private static ServerSocket serverSocket;
private Socket socketConnection;
@Override
public void run() {
while (!Application.stopServer) {
try {
socketConnection = serverSocket.accept();
new CommunicatorThread(socketConnection).start();
} catch (SocketException e) {
} catch (Exception e) {
}
}
}
private static void closeServerSocket() {
try {
if (serverSocket != null && !serverSocket.isClosed()) serverSocket.close();
} catch (Exception e) { }
}
@Override
public void interrupt() {
closeServerSocket();
super.interrupt();
}
}
我想要实现Thread
的是以正确的方式终止 s 。首先,这 ( switchStopServer()
) 是正确的方法,还是有更好的解决方案?
我对 s 有点困惑ScheduledExecutorService
,因为shutdownNow()
不会打断Thread
s,也不会ScheduledFuture.cancel(true)
(至少对我来说没有),所以我不能打断ServerSocket.accept()
。我知道,在我的示例中不需要ScheduledExecutorService
,但在我的实际应用程序中需要。