Java中有关中断的方法主要有3个:interrupt(),isInterrupted(),interrupted()。
interrupt():在一个线程(例如主线程)中调用另一个线程(例如测试线程)的interrupt()方法,即会向测试线程发出信号——线程中断状态已被设置。至于测试线程何去何从,由具体的代码实现决定。
isInterrupted():用来判断当前线程的中断状态,状态主要有:true 和 false。
interrupted():Thread的一个static方法,用来恢复中断状态。
下面我们举例说明下几个方法使用场景。
1 interrupt()不能中断在运行中的线程,它只能改变中断状态而已。
public class InterruptionInJava implements Runnable{ public static void main(String[] args) throws InterruptedException { Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");