中断机制-通过AtomicBoolean实现线程中断停止

通过AutomicBoolean

package com.nanjing.gulimall.zhouyimo.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author zhou
 * @version 1.0
 * @date 2023/10/15 2:42 下午
 */
public class InterruptDemo2 {
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println(Thread.currentThread().getName() + " atomicBoolean的值被改为true,t1程序停止");
                    break;
                }
                System.out.println("-----------hello atomicBoolean");
            }
        }, "t1").start();
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();

    }
}

中断机制-通过AtomicBoolean实现线程中断停止_第1张图片 

你可能感兴趣的:(JUC并发编程与源码分析,python,java,前端)