java.lang.InterruptedException

来源:互联网 发布:mac安装什么杀毒软件 编辑:程序博客网 时间:2024/06/14 15:12

线程的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 blocke.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)

0 0
原创粉丝点击