一方面stop線程非常粗暴,除非可能執行finally代碼塊以及釋放synchronized外,線程將直接被終止,非常粗暴,此外如果線程持有JUC的互斥鎖,還可能導致鎖來不及釋放,造成其他線程永遠等待的局面。
JUC是Lock不是自動釋放的,需要主動釋放並且要在finally代碼塊中釋放,實際上是stop一個線程並不會跳過finally代碼塊,但是如果還沒有執行try代碼塊就被stop了,那就不會執行finally代碼塊,這會造成"鎖"永遠不會釋放,而其他線程永遠無法獲取鎖的尷尬局面了。
測試代碼:
public class TestStopLockThread {
private static Lock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
Thread thread1 = new MyThread();
thread1.setName("thread1");
thread1.start();
sleep(3);
Thread thread2 = new MyThread();
thread2.setName("thread2");
thread2.start();
//直接殺死
System.out.println(nowTime() + " stop thread1");
thread1.stop();
//等待線程終止
thread1.join();
thread2.join();
}
private static class MyThread extends Thread{
@Override
public void run() {
fun1();
}
}
private static void fun1(){
System.out.println(nowTime() + Thread.currentThread().getName() + " start");
lock.lock();
//假設恰好在此刻被stop了,下面通過睡眠來模擬這種特殊情況
sleep(10);
try {
sleep(30);
System.out.println(nowTime() + Thread.currentThread().getName() + " end");
}finally {
System.out.println(nowTime() + Thread.currentThread().getName() + " finally執行");
lock.unlock();
}
}
}
過了很久很久,控制檯輸出如下:
2020/07/07 22:44:37 thread1 start
2020/07/07 22:44:40 stop thread1
2020/07/07 22:44:40 thread2 start