Thread类中有3个与interrupt相关的方法,像三胞胎一样,初学者傻傻分不清楚,举了个例子,看完就懂。
直接上代码,看注释。
- public class InterruptTaskTest {
-
- public static void main(String[] args) {
- System.out.println(Thread.currentThread() + " isInterrupted() 1: " + Thread.currentThread().isInterrupted()); // 初始false
-
- Thread.currentThread().interrupt(); // 执行后true
- System.out.println("--interrupt() 1"); // 无异常产生
- System.out.println(Thread.currentThread() + " isInterrupted() 2: " + Thread.currentThread().isInterrupted());
-
- Thread.interrupted(); // 执行后false,重置了状态
- System.out.println("++++++interrupted() 1");
- System.out.println(Thread.currentThread() + " isInterrupted() 3: " + Thread.currentThread().isInterrupted());
-
- InterruptTask task = new InterruptTask(3000); // 定时延迟3秒后,对当前线程interrupt()
-
- while (!Thread.interrupted()) { // 这时为false可以进入循环
- try {
- TimeUnit.SECONDS.sleep(2);
- } catch (InterruptedException e) {
- System.out.println("--interrupt() 2,异常信息:" + e.getMessage()); // 对sleep状态线程中断有异常
- System.out.println(task.target + " isInterrupted() 4: " + task.target.isInterrupted()); // 这时还为fasle,中断sleep线程特殊
- Thread.currentThread().interrupt(); // 必须在interrupt()一次,才能跳出循环
- System.out.println("--interrupt() 3"); // 无异常产生
- System.out.println(task.target + " isInterrupted() 5: " + task.target.isInterrupted()); // 这时为true,终止后面循环
- }
- }
-
- task.cancel();
- System.out.println("over!");
- }
- }
代码在jdk1.8执行结果:
Thread[main,5,main] isInterrupted() 1: false
--interrupt() 1
Thread[main,5,main] isInterrupted() 2: true
++++++interrupted() 1
Thread[main,5,main] isInterrupted() 3: false
--interrupt() 2,异常信息:sleep interrupted
Thread[main,5,main] isInterrupted() 4: false
--interrupt() 3
Thread[main,5,main] isInterrupted() 5: true
over!
有帮助到你的话,敲个👍。