java - 后台线程死亡时其创建的子线程是怎么处理的?
巴扎黑
巴扎黑 2017-04-17 17:35:46
0
2
423

java一个后台线程启动的线程默认也是后台线程,那么当这个后台线程死亡的时候但这个时候用户线程还未死亡,它创建的子线程是怎样处理的?是随着父线程一同死亡还是继续运行,直至run方法结束或者用户线程死亡

巴扎黑
巴扎黑

reply all (2)
洪涛
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

    PHPzhong
    this.setDaemon(true);

    Because it’s Daemon

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!