3、java多线程--Thread的三个中断相关方法

来源:互联网 发布:咏春历史 知乎 编辑:程序博客网 时间:2024/06/08 09:15

【原创代码,如有不足,欢迎指正!感谢!(* ̄︶ ̄) 】
【相互学习,天天向上】
【欢迎评论】
【一个没有天赋的女程序媛,今天又加油了!Fighting !】

Thread的三个中断相关方法:
1、interrupt(),设置线程的中断位为中断状态
2、isInterrupted()返回线程的中断位状态
3、interrupted()为static方法,返回当前线程的中断位状态,然后清除中断位
4、如果线程中断的时候发生中断异常,这时候jvm会清除线程的中断状态

/* * Thread的三个中断相关方法: * interrupt(),设置线程的中断位为中断状态 * isInterrupted()返回线程的中断位状态 * interrupted()为static方法,返回当前线程的中断位状态,然后清除中断位 */public class MyThreadRTest {    public static void main(String[] args) throws InterruptedException {        Runnable runnable = new Runnable() {            public void run() {                while (true) {                    if (Thread.currentThread().isInterrupted()) {                        System.out.println("线程被中断了");                        break;                    } else {                        System.out.println("线程没有被中断");                        try {                            Thread.sleep(500);                        } catch (InterruptedException e) {                            e.printStackTrace();                            //false,因为t0中断的时候处于sleep状态,抛出异常,清除了中断位                            System.out.println(Thread.currentThread().getName());                            System.out.println(Thread.currentThread().isInterrupted()+"  zzzz");                        }                    }                }            }        };        Thread t0 = new Thread(runnable);        t0.start();        System.out.println(t0.isInterrupted() + " xxxx");//false        Thread.sleep(2000);        t0.interrupt();//因为t0中断的时候处于sleep状态,抛出异常,清除了中断位        Thread.sleep(2000);        System.out.println(t0.isInterrupted() + " yyyy");//false,因为t0中断的时候处于sleep状态,抛出异常,清除了中断位        System.out.println("end");    }}

输出结果

false xxxx
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
java.lang.InterruptedException: sleep interrupted
Thread-0
false zzzz
线程没有被中断
at java.lang.Thread.sleep(Native Method)
at com.yy.test.thread.MyThreadRTest$1.run(MyThreadRTest.java:21)
at java.lang.Thread.run(Unknown Source)
线程没有被中断
线程没有被中断
线程没有被中断
false yyyy
end
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
线程没有被中断
。。。。。。。。。。
由于中断的时候,t0处于sleep状态,发生中断异常,并清除了t0的中断状态,所以不能打印出线程被中断。

原创粉丝点击