多线程之两阶段终止模式及interrupt详解

优雅的打断另一个线程,并让其料理后事

interrupt能打断sleep、wait、join。

注意:sleep被打断产生的异常(InterruptedException )会将打断标志设为false。

package cn.itcast.test;
import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TwoPhaseTermination")
public class Test13 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();

        Thread.sleep(3500);
        log.debug("停止监控");
        tpt.stop();
    }
}

@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination {
    // 监控线程
    private Thread monitorThread;

    // 启动监控线程
    public void start() {

        monitorThread = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                // 是否被打断
                if (current.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();

                    //重新设置打断标记,因为sleep会将打断标志设为false
                    current.interrupt();
                }
            }
        }, "monitor");
        monitorThread.start();
    }
    // 停止监控线程
    public void stop() {
        monitorThread.interrupt();
    }
}

能打断park()方法;

park 挂起线程 ,能让park后面的代码都不运行 ,


private static void test3() throws InterruptedException {
    Thread t1 = new Thread(() -> {
        log.debug("park...");
        LockSupport.park();
        log.debug("unpark...");
        log.debug("打断状态:{}", Thread.currentThread().isInterrupted());
    }, "t1");

    t1.start();
    sleep(1);
    t1.interrupt();
}

猜你喜欢

转载自blog.csdn.net/wang_nian/article/details/109133844