2012-11-25 26 views
0

這是我使用線程的一個小程序片段。線程不停留活 - IllegalStateException

JOptionPane.showMessageDialog(null, "Before: " + thread.isAlive()); 
if (!thread.isAlive()) { 
    JOptionPane.showMessageDialog(null, "Thread is not alive."); 
    thread.start(); 
} 
JOptionPane.showMessageDialog(null, "After: " + thread.isAlive()); 

此代碼使用按鈕激活。當我第一次按下按鈕時,我正確地得到「Before:false」,然後「After:true」。 當我再次按下按鈕時,我錯誤地得到「Before:false」,然後「After:true」,但是期望Before:true,因爲我沒有銷燬線程或覆蓋變量。

我認爲,這是什麼原因造成這IllegalStateException異常我得到(糾正我,如果我錯了,對了!)

任何人都可以向我解釋什麼,我做錯了什麼?

編輯:

public class SomeClass extends Applet 
{ 

private ClassThatExtendsThread thread; 

public void init() 
{ 
    super.init(); 

    //Some UI elements are created here. 

    thread = new ClassThatExtendsThread (/*there are some parameters*/); 
} 
+0

你在哪裏以及如何開始'thread'? – NPE

+1

*我相信這是什麼導致我得到的IllegalStateException *:什麼是* this *?什麼是異常的完整堆棧跟蹤?我寧願說這是你得到異常的結果*,這可能導致線程死亡。 –

+0

我已經添加了線程類如何存儲和實例化 –

回答

2

一旦線程完成運行,它被認爲是死的。在同一線程調用isAlive此時將始終返回false的結果。該JavaDoc for Thread確實提到這一點:

 
public final boolean isAlive() 

Tests if this thread is alive. A thread is alive if it has been started and has not 
yet died. 

如果不重新實例化你的線程的實例在兩者之間調用您的代碼段,那麼你一定會得到一個IllegalStateException。這是因爲你嘗試啓動已終止線程:

if (!thread.isAlive()) { 
    JOptionPane.showMessageDialog(null, "Thread is not alive."); 
    thread.start(); 
} 

以供將來參考,請注意您可以通過getState方法,它應該分析錯誤,在至少幫助查詢線程狀態。

+0

所以當它到達run()函數的末尾時它會結束運行嗎?如何讓此類中的其他按鈕調用線程中未運行()的其他函數。也許有一個循環內運行?但是它永遠不會退出。 –

+0

那麼如何防止它終止?我不想重新實例化,因爲我失去了一切。 –

+0

你在做什麼聽起來不像線程的用例。你想要的是一個監聽器類,你也可以根據主UI中發生的事件進行調度。 – Perception

0

您必須存儲線程變量作爲類成員只有一次創建它。最有可能的是,您將它作爲局部變量存儲並在每次按下按鈕時創建它。

+0

我已經添加了線程類如何存儲和實例化 –

+0

線程在做什麼? –

+0

只更改一些內部變量,僅此而已。 –