4.1.4 大厂面试题中断机制考点
如何停止中断运行中的线程?
通过一个volatile变量实现
package com.nanjing.gulimall.zhouyimo.test;import java.util.concurrent.TimeUnit;/*** @author zhou* @version 1.0* @date 2023/10/15 2:34 下午*/
public class InterruptDemo {static volatile boolean isStop = false; //volatile表示的变量具有可见性public static void main(String[] args) {new Thread(() -> {while (true) {if (isStop) {System.out.println(Thread.currentThread().getName() + " isStop的值被改为true,t1程序停止");break;}System.out.println("-----------hello volatile");}}, "t1").start();try {TimeUnit.MILLISECONDS.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {isStop = true;}, "t2").start();}
}