JAVA中的线程中断
1.Thread.interrupt() —— 设置interrupted为true
源码:
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
只有线程自身可以中断自身的运行,不然checkAccess()就会抛出SecurityException
java使用一个中断位来标记一个线程是否已经中断,中断位的作用就是提醒程序员线程达到了中断的条件
在调用wait()系列、sleep()系列、join()系列方法后中断位会被清除,但是并不会中断线程
当前线程会收到InterruptedException,可以做出一些处理(退出线程等)
2.t.isInterrupted()
源码:
public boolean isInterrupted() { return isInterrupted(false); }
检测线程t是否已经进入中断状态,自己检测自己
3.Thread.interrupted()
源码:
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
检测某个线程是否已经进入中断状态,由其他线程代劳,但是会清除中断位
意味着如果调用该方法两次,第二次返回的结果将为false
第一次:false -> true , 第二次: true -> false
线程中断测试:
<pre style="font-family: 宋体; font-size: 10.5pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">public class TestInterruptException implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new TestInterruptException());
t.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//中断该线程实例
t.interrupt();
}
@Override
public void run() {
//while(true)也要在try-catch块里面
int number = 0;
try {
while (true) {
checkNum(number);
number++;
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName() + " is interrupted");
}
}
private void checkNum(int number) throws InterruptedException {
if (number % 50000000 == 3) {
System.out.print(number);
}
//检测当前线程是否已经中断了
if (Thread.interrupted()) {
//发出通知线程已经处于中断状态
throw new InterruptedException();
}
}
}