多线程 -- interrupt()方法

来源:互联网 发布:怎么注册淘宝客账号 编辑:程序博客网 时间:2024/06/11 00:33

interrupt()方法不会中断一个正在运行的线程,它用于提前退出线程的阻塞状态,也就是说当线程通过Object.wait() / Thread.sleep() / Thread.join() / 方法进入阻塞状态后,如果调用线程中断方法,该线程会收到一个InterruptedException中断异常,可以在catch中编写自己需要的代码。


public class InterruptThread {public static void main(String[] args){Thread t1 = new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubtry{long time = System.currentTimeMillis();while(System.currentTimeMillis()- time <1000){}System.out.println("T1_normal");}catch(Exception e){System.out.println("T1_Exception e="+e);}}},"t1");t1.start();t1.interrupt();Thread t2 = new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep(1000);System.out.println("T2_sleep_normal");} catch (InterruptedException e) {// TODO Auto-generated catch blockSystem.out.println("T2_sleep_Exception e="+e);}}},"t2");t2.start();t2.interrupt();Thread t4 = new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubtry {this.wait(1000);System.out.println("T4_wait_normal");} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println("T4_wait_Exception e="+e);}}},"t4");t4.start();t4.interrupt();Thread t5 = new Thread(new Runnable(){@Overridepublic synchronized void run() {// TODO Auto-generated method stubtry {this.wait(1000);System.out.println("T5_wait_normal");} catch (InterruptedException e) {// TODO Auto-generated catch blockSystem.out.println("T5_wait_Exception e="+e);}}},"t5");t5.start();t5.interrupt();try{t5.start();System.out.println("T5_again_wait_normal");}catch(Exception e){System.out.println("T5_again_wait_Exception e="+e);}}}


打印出来的log(顺序随机):

T2_sleep_Exception e=java.lang.InterruptedException: sleep interrupted
T4_wait_Exception e=java.lang.IllegalMonitorStateException
T5_again_wait_Exception e=java.lang.IllegalThreadStateException
T5_wait_Exception e=java.lang.InterruptedException
T1_normal


1.线程T1:

log:T1_normal

 可以看出interrupt()方法不会中断正在执行的线程。


2.线程T2:

log:T2_sleep_Exception e=java.lang.InterruptedException: sleep interrupted

可以看出sleep中断


3.线程T4:

log:T4_wait_Exception e=java.lang.IllegalMonitorStateException

这个是在没有被锁定的对象中,调用wait()方法产生的异常


4.线程T5:

log:T5_wait_Exception e=java.lang.InterruptedException

wait中断

log:

T5_again_wait_Exception e=java.lang.IllegalThreadStateException

重复调用线程的start()方法产生的异常

0 0
原创粉丝点击