线程的中断interrupt()方法

2019-08-13  本文已影响0人  叫我胖虎大人

线程的6个状态

已经抛弃中断方法

原因:调用上述的方法会立即停止调用该方法的线程,会导致线程清理问题.此外,被通知的线程会立即释放锁,造成数据的不同步.

目前的使用方法

注意:调用interrupt()方法并不会使得线程中断,而是使得线程的中断标志置为true


代码示例

public class InterruptDemo {
    public static void main(String[] args) throws InterruptedException {
        Runnable interruptTask = new Runnable() {
            int i = 0;
            @Override
            public void run() {
                try {
                    //在正常运行任务时,经常进行本线程的中断标志,如果被设置了终端标志就自行停止线程
                    while (!Thread.currentThread().isInterrupted()){
                        //休眠100ms
                        Thread.sleep(100);
                        i++;
                        System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") loop " + i);
                    }
                }catch (InterruptedException e){
                    //在调用阻塞方法时正确处理InterruptedException异常。(例如,catch异常后就结束线程。)
                    System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState()
                                        + ") catch InterruptedException.");
                }
            }
        };
        Thread t1 = new Thread(interruptTask,"t1");
        System.out.println(t1.getName() +" ("+t1.getState()+") is new.");

        // 启动“线程t1”
        t1.start();
        System.out.println(t1.getName() +" ("+t1.getState()+") is started.");

        // 主线程休眠300ms,然后主线程给t1发“中断”指令。
        Thread.sleep(300);
        t1.interrupt();
        System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");

        // 主线程休眠300ms,然后查看t1的状态。
        Thread.sleep(300);
        System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
    }
}

运行结果

t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted.
t1 (RUNNABLE) catch InterruptedException.
t1 (TERMINATED) is interrupted now.

上一篇 下一篇

猜你喜欢

热点阅读