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)

猜你喜欢

转载自blog.csdn.net/enjoyinwind/article/details/51702130
今日推荐