前言:
想要实现的功能是,
kill
命令结束正在执行的Java进程时,中断(interrupt)正在执行的Java进程里的线程。原来的想法以为,使用kill
命令会自动中断(interrupt)那些正在执行的线程,结果和想像的不太一样。在网上找了一下,找到了一个方法来实现这个些想法
正文:
主要方法如下:
添加一个ShutdownHook。这样在使用
kill
、kill -15
、kill -2
命令或Ctrl+C
结束Java进程时,会调用添加的ShutdownHook。这样的话,我们就可以在ShutdownHook里,进行中断我们想要中断的线程了。
代码如下:
public class SubThreadKilledTester {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Interrupting threads");
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
for (Thread runningThread : runningThreads) {
// 判断线程是否是我们要测试的线程
if (runningThread.getName().equals("InteruptThread")) {
// 如果线程没有被中断,我们进行中断他
if (!runningThread.isInterrupted()) {
System.out.println("InteruptThread is not interrupted, we are going to interupt it");
runningThread.interrupt();
}
}
}
System.out.println("Shutdown hook ran!");
}
});
// 创建并启动子线程类
InteruptThread thread = new InteruptThread();
thread.start();
}
/**
* 用来测试要中断的线程类
*/
static class InteruptThread extends Thread {
public InteruptThread() {
this.setName("InteruptThread");
}
@Override
public void run() {
while (true) {
try {
while (true) {
// 打印个时间
System.out.println(System.currentTimeMillis());
// 等待10秒
TimeUnit.SECONDS.sleep(10);
}
} catch (InterruptedException e) {
System.out.println("oh yeah, InteruptThread is interrupted");
break;
} catch (Exception e) {
System.out.println("unknown exception ocurred");
break;
}
}
}
}
}
启动上面的程序后,直接使用Ctrl+C
或 在shell
里使用kill/kill -15/kill -2
(kill -2 没有进行测试,参考文章上写可以),就可以中断我们创建的线程了。log如下:(这里是使用Ctrl+C中断的)
491649567672
^C
Interrupting threads
InteruptThread is not interrupted, we are going to interupt it
Shutdown hook ran!
oh yeah, InteruptThread is interrupted