Thread有三个方法:
1. interrupt //线程被标识为中止状态,可是线程仍是会继续运行
2.isInterrupted //若是某个线程被标识为中止状态,那么就返回true,不然false。线程中止结果也是false
3.interrupted(静态) //判断"当前线程"是否被标识为中止状态,判断后就将"当前线程"的中止状态清除 java
InterruptedException异常:
1.线程处在sleep中被interrupt或在interrupt后sleep,会抛出InterruptedException异常
2.线程处在wait中被interrupt会抛出InterruptedException异常
3.若是对象当前没有得到锁,而调用wait/notify/notifyAll会抛出InterruptedException异常 ide
测试用例1: 测试
public class InterruptTest { public static class MyThread extends Thread{ public MyThread(Runnable target, String name) { super(target, name); } public MyThread(String name) { super(name); } @Override public void run() { super.run(); System.out.println(Thread.currentThread().getName()+" 运行了!"); while (true) { if(Thread.currentThread().isInterrupted()){ System.out.println("线程中止了!"); break; } } } } public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread("runThread"); thread.start(); //使main线程interrupt Thread.currentThread().interrupt(); System.out.println("Thread.interrupted() ="+Thread.interrupted()); System.out.println("Thread.interrupted()= "+Thread.interrupted()); //使runThread线程interrupt thread.interrupt(); System.out.println("thread.isInterrupted() ="+thread.isInterrupted()); System.out.println("thread.isInterrupted() ="+thread.isInterrupted()); } }结果:
----------------------------------------- spa
测试用例2: 线程
public class InterruptTest { public static class MyThread extends Thread{ public MyThread(String name) { super(name); } @Override public void run() { super.run(); System.out.println(Thread.currentThread().getName()+" 运行了!"); while (true) { if(Thread.currentThread().isInterrupted()){ System.out.println("线程被Interrupt了,而且当前线程的Interrupt状态为: "+Thread.currentThread().isInterrupted()); break; } } try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("进入catch了,当前线程的Interrupt状态为: "+Thread.currentThread().isInterrupted()); e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread("runThread"); thread.start(); thread.interrupt(); } }结果: runThread 运行了! 线程被Interrupt了,而且当前线程的Interrupt状态为: true 进入catch了,当前线程的Interrupt状态为: false java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at thread.InterruptTest$MyThread.run(InterruptTest.java:21)