线程的阻塞、中断小结

来源:互联网 发布:手柄震动测试软件 编辑:程序博客网 时间:2024/06/07 10:23

interrupt

线程不能在运行时被中断,它的作用是在线程被阻塞时抛出中断异常,然后线程可以继续执行。

中断类型

1. 线程执行碰到object.wait(),需要等待notify()
2. 碰到Thread.sleep()
3. 调用别的线程的join()
4. I/O阻塞
5. 拿不到锁对象


其中,1.2.3可以被中断,4.5不可被中断。

验证代码段1:

 static Runnable runnable = new Runnable() {        @Override        public void run() {           for (int i=0;i<1000;i++){               System.out.println(i);           }        }    };    public static void main(String[] args){        Thread thread = new Thread(runnable);        thread.start();        try {            Thread.sleep(5);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("befor interrupt");        thread.interrupt();        System.out.println("after interrupt");    }
输出:
479
480
481
befor interrupt
482
after interrupt
483
484
485

即已经在执行的线程不会被中断,会一直执行完。

代码段2:

 static Runnable runnable = new Runnable() {        @Override        public void run() {            System.out.println("beforSleep time = " + System.currentTimeMillis());            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                System.out.println("InterruptedException");            }            System.out.println("afterSleep time = " + System.currentTimeMillis());        }    };    public static void main(String[] args){        Thread thread = new Thread(runnable);        thread.start();        try {            Thread.sleep(5);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("befor interrupt");        thread.interrupt();        System.out.println("after interrupt");    }

输出:
beforSleep time = 1499741340999
befor interrupt
after interrupt
InterruptedException
afterSleep time = 1499741341004


从打印的时间看,Sleep(5000)开始后,很快就被打断了,sleep的时间不到1秒。