【发布时间】:2016-05-16 11:43:32
【问题描述】:
我正在尝试关闭应用程序,只要有任何致命
错误/异常出现但在关闭应用程序之前我当前
线程/任务应该完成,所以我写了mainThread.join()
在run() 内部,它在没有异常的情况下工作正常。但每当我
doTask() 那个时候抛出异常 join() 永远等待。
public class POC
{
public void doTask() throws Exception
{
throw new Exception("Fatal Error");
//throw new Exception("Fatal Error"); By commenting working fine.
}
public static void main(String[] args)
{
POC ob = new POC();
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try
{
System.out.println("Join() Start");
mainThread.join();
System.out.println("Join() End"); //Why this is not printing?
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
try
{
System.out.println("Before doTask()");
ob.doTask(); //User Defined Run()
System.out.println("After doTask()");
}
catch (Exception ex) // FATAL
{
System.err.println("Exception : " + ex.getLocalizedMessage());
System.exit(-1);
}
}
}
OutPut : 0
Before Run()
Exception : Fatal Error
Join() Start
为什么System.out.println("Join() End"); 不打印?
【问题讨论】:
-
> 请告诉我,有什么解决方案可以解除死锁并强制关闭jvm。
标签: multithreading concurrency process jvm shutdown-hook