1回复
4年前
Java如何kill一个没有中断的线程?
刚刚再调试程序发现一个比较基础的问题,弄成了demo代码.
场景是,在jvm运行时干掉XX线程,代码如下:
public static void main(String[] args) throws InterruptedException {
//**//
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
//一个死循环的job 没有sleep、wait...
}
}
}) {{
this.setName("test-Thread-1");
}}.start();
//*模拟一个无法中断的线程*//
Thread _thread = null;
Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces();
for (Thread thread : threadMap.keySet()) {
if (thread.getName().equals(Thread.currentThread().getName())) {
continue;
}
if (thread.getName().equals("test-Thread-1") && thread.isAlive()) {
_thread = thread;
thread.interrupt();
}
}
Thread.sleep(1000);
System.out.println(_thread.isAlive()); //true
System.out.println(_thread.isInterrupted());//true
//死循环cpu飙高
System.exit(0);
}
3212 阅读