java ctrl+c(kill 2)打断过程
本文主要介绍用ctrl+c打断java进程后的情况
- 没有shutdown hook
- 存在shutdown hook
当程序不存在shutdown hook的时候
程序会直接退出,即使有线程在跑,也不会产生任何打断信号给线程,例如:
public class BB{
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
});
t.start();
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("interrupted.");
}
}
}
}
程序会直接推出,进程资源被回收。
当存在shutdown hook的情况
有shutdownhook,shutdownhook结束后,即使有进程没有结束,进程还是会退出,例如:
public class AA {
public static void main(String[] args) {
Thread aaa = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("interrupted.");
}
}
}
});
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
}
}
}, "Data"));
aaa.start();
}
}
ctrl+c打断后执行shutdown hook,hook时空的,所以很快结束,上面的线程被系统回收。我们正常情况下是在hook中打断线程,并作join操作,做好善后处理:
public class AA {
public static void main(String[] args) {
Thread aaa = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("interrupted.");
}
}
}
});
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
try{
aaa.interrupt();
aaa.join();
} catch (InterruptedException e) {
System.out.println("hhh");
Thread.currentThread().interrupt();
}
}
}, "Data"));
aaa.start();
}
}
此时ctrl+c打断后会县打断线程,线程结束后,这个shutdown hook结束,进程结束。