理解interrupt

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());
		
	}
}
結果:
Thread.interrupted() =true
Thread.interrupted()= false
thread.isInterrupted() =true
thread.isInterrupted() =true
runThread 運行了!
線程中止了!

----------------------------------------- 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)
相關文章
相關標籤/搜索