关于线程终止:李四一旦进到工作状态,他就会按照行动指南上的步骤去进行工作,不完成是不会结束的。但有时我们 需要增加一些机制,例如老板突然来电话了,说转账的对方是个骗子,需要赶紧停止转账,那张三该如 何通知李四停止呢?这就涉及到我们的停止线程的方式了。
线程终止的方法:
1、使用自定义标识符来终止线程(需要给标志位上加 volatile 关键字)
public class CsdnDemo {
//1.声明一个自定义标识符
private volatile static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (!flag){
System.out.println("正在转账...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("差点误了大事");
});
thread.start();
Thread.sleep(3000);
//终止线程
System.out.println("停止交易");
flag = true;
}
}
2、调用 interrupt() 方法来通知
public class CsdnDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (!Thread.interrupted()){//两种方式皆可
// while (!Thread.currentThread().isInterrupted()){
System.out.println("正在转账...");
}
System.out.println("差点误了大事");
});
thread.start();
Thread.sleep(100);
//终止线程
thread.interrupt();
System.out.println("终止交易");
}
}
interrupted和isinterrupted的区别
1、interrupted属于静态方法,所有程序都可以直接调用的全局方法,而isinterrupted属于某个实例 的方法。
2、interrupted在使用完之后会重置中断标识符,而isinterrupted不会重置中断表示。