优雅的结束一个线程

新同事在维护我们两年前的代码时候问了我这个问题。之前项目中我们都类似喜欢用如下方式结束一个线程:

// Create and start the thread MyThread thread = new MyThread(); thread.start(); // Do work... // Stop the thread thread.allDone = true; class MyThread extends Thread { boolean allDone = false; // This method is called when the thread runs public void run() { while (true) { // Do work... if (allDone) { return; } // Do work... } } }

 

该方法比较通用,在涉及到socket 通讯、I/O操作的时候可能需要比较小心,控制好资源关闭开启情况。

你可能感兴趣的:(thread,socket,通讯)