java经常使用的结束一个运行中的线程的方法有3中:使用退出标志,使用interrupt方法,使用stop方法。java
即在线程内部定义一个bool变量来判断是否结束当前的线程:安全
public class ThreadSafe extends Thread { public volatile boolean exit = false; public void run() { while (!exit){ //do work } } public static void main(String[] args) throws Exception { ThreadFlag thread = new ThreadFlag(); thread.start(); sleep(5000); // 主线程延迟5秒 thread.exit = true; // 终止线程thread thread.join(); System.out.println("线程退出!"); } }
这种状况通常是将线程的任务放在run方法中的一个while循环中,而由这个bool变量来对while循环进行控制。socket
这种方法须要判断当前的线程所处于的状态:
(1)当前线程处于阻塞状态时
线程处于阻塞状态通常是在使用了 sleep,同步锁的 wait,socket 中的 receiver,accept 等方法时,会使线程处于阻塞状态。线程
public class ThreadInterrupt extends Thread { public void run() { try { sleep(50000); // 延迟50秒 } catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); System.out.println("在50秒以内按任意键中断线程!"); System.in.read(); thread.interrupt(); thread.join(); System.out.println("线程已经退出!"); } }
注意这种状况写,使用 interrupt 方法结束线程的时候,必定要先捕获 InterruptedException 异常以后经过 break 来跳出循环,才能正常结束 run 方法。code
(2)线程未处于阻塞状态时get
使用 isInterrupted() 判断线程的中断标志来退出循环。当使用 interrupt() 方法时,中断标志就会置 true,和使用自定义的标志来控制循环是同样的道理。同步
public class ThreadSafe extends Thread { public void run() { while (!isInterrupted()) { //非阻塞过程当中经过判断中断标志来退出 try { Thread.sleep(5*1000); //阻塞过程捕获中断异常来退出 } catch (InterruptedException e) { e.printStackTrace(); break; //捕获到异常以后,执行 break 跳出循环 } } } }
public class Main { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(3000); // 间隔3秒后 myThread.stop(); // 结束线程 System.out.println("结束了"); } }
建议使用标志位和interrupt方法来结束线程,stop方法已经不建议再被使用了。
由于采用 stop 是不安全的,主要影响点以下:it