一方面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