概述
一个线程不应该由其他线程来强制中断或者停止,而是应该由线程本身来自行停止。
因此,Thread.stop、Thread.suspend、Thread.resume 已经被废弃。
对于一个线程调用interrupt方法时
1、如果线程处于被阻塞状态(例如处于sleep, wait, join 等状态),那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常。
2、 如果线程处于正常活动状态,那么会将该线程的中断标志设置为 true,仅此而已。被设置中断标志的线程将继续正常运行,不受影响。
interrupt不能真正的中断线程,需要线程自身进行配合。
1、在正常运行任务时,经常检查本县城的中断标志位。如果设置了,则自行停止线程
Thread thread = new Thread(() -> {while (!Thread.interrupted()) {// 检测到中断时,跳出中断?}});thread.start();// 一段时间以后thread.interrupt();
2、在调用阻塞方法时正确处理InterruptedException异常。(例如,catch异常后就结束线程。)
public class RunnableDemo implements Runnable{public void run(){try {Thread.currentThread().sleep(1000L);System.out.println(Thread.currentThread().getName()+" "+Thread.currentThread().isInterrupted());}catch(InterruptedException e){// 处理中断抛出的异常System.out.println(Thread.currentThread().getName()+" \n "+e.toString());}}}
常用的中断方法
public void interrupt() // 将线程的中断状态设为truepublic boolean isInterrupted() //返回线程的中断状态public boolean static boolean interrupted()只能通过Thread.interrupted()调用。有两步操作:1是返回当前线程的中断状态 2、将当前线程的中断设为false。
一个例子
public void run(){do something;// 检测到中断后,才进行某个操作。比如:释放资源??if(isInterrupted()){do something;Thread.interrupted();}}
