不推荐使用
通过查阅JDK文档,我们不难发现Thread为我们提供了一个stop方法,只要使用stop方法,就立即停止线程,但是发现stop()方法 被标注为废弃的方法,因为这个方法会强行把执行到一半的线程终止,还会释放锁,可能导致线程安全问题,引发一些数据不一致或者我们没发预估的问题,所以不建议使用。
推荐使用
这里的优雅指的是可以让线程有时间做好收尾工作,所以我们使用interrupt加入中断标记来停止线程。
interrupt方法只是一个标记,并没有中断的作用,所以我们收到这个消息后可以做出合理的处理,比如让自己停止执行程序(跳出循环/抛出异常),或者拿到标记后继续执行一些程序后再慢慢停止。
例子
public static void main(String[] args) {
//创建 interrupt-1 线程
Thread thread = new Thread(() -> {
while (true) {
//判断当前线程是否中断
if (Thread.currentThread().isInterrupted()) {
System.out.println("线程1 接收到中断信息,中断线程...中断标记:" + Thread.currentThread().isInterrupted());
//跳出循环,结束线程
break;
}
System.out.println(Thread.currentThread().getName() + "线程正在执行...");
}
System.out.println("跳出循环之后,中断标记为: " + Thread.currentThread().isInterrupted());
//根据业务决定要不要清空标志,清空后来保证可继续访问和记录日志
//Thread.currentThread().interrupted();
//System.out.println("清空标志之后为: "+Thread.currentThread().isInterrupted());
}, "interrupt-1");
//启动线程 interrupt-1
thread.start();
//创建 interrupt-2 线程
new Thread(() -> {
int i = 0;
while (i < 20) {
System.out.println(Thread.currentThread().getName() + "线程正在执行...");
if (i == 8) {
System.out.println("设置线程中断....");
//通知线程1 设置中断通知
thread.interrupt();
}
i++;
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "interrupt-2").start();
}