java join 异常_Java:守护进程:thread.join()没有完成,当在一个线程中抛出异常时...
我寫了一個Java守護進程(一個實現守護進程和Runnable的類),現在我遇到了以下問題:
在init()中,我創建了一個新線程 . Thread thread = new Thread(this); 在start()中我啟動新線程 . thread.start() . 在運行中我做了很多不同的事情......然后發生異常 . (在我的例子中:NullPointerException . ) .
現在發生的是我在run()中捕獲異常并調用stop() . 在那里我調用 thread.join() ,但是這永遠不會完成,并且不會拋出InterruptedException . 我怎么解決這個問題?
在run()中,我在while循環中做了一些事情
private Thread thread;
public void init() {
// if init is successful: this.thread = new Thread(this);
// if init is not successful: call stop()
}
public void run() {
try{
// do something
while (!this.stopping)
{
// do somthing
}
} catch (Exception e) {
//do something and then call stop()
}
}
public void stop() {
this.stopping = true;
thread.join(); // catch InterruptedException if it did not work
// do some more things
}
這就是引發異常的地方 . 停止是易失性的,一旦調用停止,我就將其設置為true .
謝謝 :-)
我得到了很多答案,但我仍然沒有解決這個問題 . 每個人都說我不應該在我的run()或init()方法中手動調用stop() . 我的問題是,當init()或run()發生異常時,我想真正停止該程序 . 完成它,以便程序不再運行 . 我不知道如何在不調用stop()的情況下實現這一點 . 只需等待run()完成就不起作用,因為它會停止然后永遠不會調用stop() . 我還是不確定如何處理異常問題 .
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java join 异常_Java:守护进程:thread.join()没有完成,当在一个线程中抛出异常时...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 完美破解nbsp;iPhone“一键解锁
- 下一篇: 20190216-Java 教程(菜鸟教