private class StopServer extends Thread
{
public void start()
{
this.setDaemon(true);
super.start() ;
}
@Override
public void run() {
ServerSocket serverSocket = null ;
Socket socket = null ;
try {
serverSocket = new ServerSocket(8001) ;
while (true) {
socket = serverSocket.accept();
String line = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
if (line.equals("shutdown"))
{
socket.getOutputStream().write("ok, start stop the server....\r\n".getBytes());
socket.getOutputStream().flush() ;
System.out.println("start a new thread to stop the server....") ;
//新创建的子线程
new Thread() {
public void start() {
setDaemon(true);
super.run();
}
public void run() {
System.out.println("start stopServer Thread...");
EchoServer2.this.stop();
}
}.start();
break ;
} else
{
if (!socket.isClosed())
socket.close();
}
}
}
catch (IOException e)
{
System.err.println("daemon thread exception: " + e);
e.printStackTrace();
}
finally {
System.out.println("stop stopServer...");
if(serverSocket != null && !serverSocket.isClosed())
try
{
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
if(socket != null && !socket.isClosed())
try {
socket.close();
}catch (IOException e)
{
e.printStackTrace() ;
}
}
}
}
This is a background thread of a server I wrote yesterday. This thread is mainly used to monitor port 8001. If a shutdown command is received, the server will be shut down. After shutting down the server, I started a new thread, which is this background thread. When the sub-thread is actually running, the server is not shut down, so I judge that the sub-thread will die along with the entire background thread. It seems that the operating system has to read the book again. Sorry to bother everyone
This is a background thread of a server I wrote yesterday. This thread is mainly used to monitor port 8001. If a shutdown command is received, the server will be shut down. After shutting down the server, I started a new thread, which is this background thread. When the sub-thread is actually running, the server is not shut down, so I judge that the sub-thread will die along with the entire background thread. It seems that the operating system has to read the book again. Sorry to bother everyone
Because it’s Daemon