一、LockSapport与线程中断
1、线程中断机制
1.什么是中断机制
2、中断机制的三大方法
public void interrupt()
实例方法interrupt()仅仅是设置线程的中断状态为true,发起一个协商不会立刻停止线程
public void isInterrupted()
判断当前线程是否被中断
public static void interrupted()
判断线程是否被中断清除当前中断状态
3、面试题中断机制考点
1、如何停止中断运行中的线程?
通过volatile变量实现
public static volatile boolean interrupt = false;
public static void method1() {
new Thread(() -> {
while (true) {
if (interrupt) {
System.out.println("中断状态程序停止" + interrupt);
break;
}
System.out.println("Hello volatile");
}
}).start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
interrupt = true;
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
public static AtomicBoolean isInterrupt = new AtomicBoolean(false);//原子Boolean 用于操作多线程
public static void method2() {
new Thread(() -> {
while (true) {
if (isInterrupt.get()) {
System.out.println("中断状态程序停止" + interrupt);
break;
}
System.out.println("Hello AtomicBoolean");
}
}).start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// interrupt = true;
isInterrupt.set(true);
System.out.println(Thread.currentThread().getName() + "执行完毕");
}