理解interrupt

Thread有三个方法:
1. interrupt                //线程被标识为停止状态,但是线程还是会继续运行
2.isInterrupted            //如果某个线程被标识为停止状态,那么就返回true,否则false。线程停止结果也是false
3.interrupted(静态)    //判断"当前线程"是否被标识为停止状态,判断后就将"当前线程"的停止状态清除

InterruptedException异常
1.线程处在sleep中被interrupt或在interrupt后sleep,会抛出InterruptedException异常
2.线程处在wait中被interrupt会抛出InterruptedException异常
3.如果对象当前没有获得锁,而调用wait/notify/notifyAll会抛出InterruptedException异常

测试用例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());
		
	}
}
结果:
Thread.interrupted() =true
Thread.interrupted()= false
thread.isInterrupted() =true
thread.isInterrupted() =true
runThread 运行了!
线程停止了!

-----------------------------------------

测试用例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)


你可能感兴趣的:(理解interrupt)