1.使用API
isInterrupted():判断当前线程是否停止,false表示没有停止,true表示停止
interrupt():标记线程停止,只是打了标记不是强制停止线程
interrupted():静态方法调用会将标记状态设置为false,
public class MyInterrupt implements Runnable {
@Override
public void run() {
Thread thread = Thread.currentThread();
// 判断当前线程标记状态
while(!thread.isInterrupted()){
System.out.println("线程执行中");
}
System.out.println("线程执行完毕");
}
public static void main(String[] args) throws InterruptedException {
MyInterrupt interrupt = new MyInterrupt();
Thread thread = new Thread(interrupt);
thread.start();
Thread.sleep(1);
// 线程停止标记
thread.interrupt();
}
}
抛出InterruptedException异常会重置中断标记
package com.cairenhui;
/**
- 实现线程中断方式
*/
public class Interrupt implements Runnable{
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
Thread t = Thread.currentThread();
System.out.println("hhhhhhhh");
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
System.out.println(Thread.currentThread().isInterrupted());
// 停止线程
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws InterruptedException {
Interrupt t = new Interrupt();
Thread thread = new Thread(t);
thread.start();
Thread.sleep(100);
thread.interrupt();
}
}
线程睡眠的时候停止线程抛出InterruptedException异常会将中断标志置为false,可以
Thread.currentThread().interrupt();重置标记