java.lang.InterruptedException

線程的interrupt()調用不管是在該線程的阻塞方法調用前或調用後,都會導致該線程拋出InterruptedException;

(1)interrupt調用在阻塞方法調用前;

public class InterruptTest {
	public static class TestThread extends Thread{
		public volatile boolean go = false;
		public void run(){
			test();
		}
		
		private synchronized void test(){
			System.out.println("running");
			
			while(!go){
				
			}
			try {
				if(isInterrupted()){
					System.out.println("Interrupted");
				}
				
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.out.println("InterruptedException");
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestThread thread = new TestThread();
		thread.start();
		
		thread.interrupt();
		thread.go = true;
	}

}
輸出:

running
Interrupted
java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at InterruptTest$TestThread.test(InterruptTest.java:20)
at InterruptTest$TestThread.run(InterruptTest.java:6)

(2)interrupt調用在阻塞方法調用後;

public class InterruptTest {
	public static class TestThread extends Thread{
		public volatile boolean go = false;
		public void run(){
			test();
		}
		
		private synchronized void test(){
			System.out.println("running");
	
			try {
				if(isInterrupted()){
					System.out.println("Interrupted");
				}
				
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.out.println("InterruptedException");
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestThread thread = new TestThread();
		thread.start();
		
		try {
			Thread.currentThread().sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		thread.interrupt();
	}

}
輸出:

running
InterruptedException
java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at InterruptTest$TestThread.test(InterruptTest.java:20)
at InterruptTest$TestThread.run(InterruptTest.java:6)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章