2 回答

TA貢獻1829條經驗 獲得超9個贊
提供的代碼中有很多錯誤,我必須提前幾步才能正確回答問題。
1. 您使用的是哪個線程構造函數?
Thread 提供了幾種構造函數,它們將字符串、Runnable 或線程組作為參數。您的函數構造線程,其結果simulation.simulate()必須是上述返回類型之一才能編譯。我很確定您沒有意識到此時整個simulate函數正在運行并在線程啟動之前完成。另請注意,您隨后定義了具有空實現 (the { })的抽象 Thread 類。
嘗試像這樣初始化線程:
final Simulate simulation = new Simulate(0.1, Main.house);
Thread simThread = new Thread(simulation::simulate);
這會將方法simulate本身作為Runnable參數傳遞給 Thread 構造函數。請注意,要使其工作,模擬方法必須是 return-type void。
2. 外部函數應該如何訪問局部變量?
在您的方法中,您聲明了一個僅對方法本身可見的變量。任何外部代碼應該如何解決它?您至少需要返回局部變量(因此將其公開):
public static Thread simulate(ActionEvent e){
final Simulate simulation = new Simulate(0.1, Main.house);
final Thread simThread = new Thread(simulation::simulate);
simThread.start();
return simThread;
}
現在外部調用者將接收已創(chuàng)建的線程,然后可以中斷它 theReturnedValue.interrupt()
或者,您可以將 id 分配給您創(chuàng)建的線程并在內部管理它們,但這超出了本答案的范圍。
3. 你認為interrupt是什么?
沒有(合法的)方法可以阻止線程運行,因此唯一interrupt能做的就是向線程發(fā)送“請求”以停止工作。由于您還沒有發(fā)布simulate方法,我只能猜測那里會發(fā)生什么。
interrupt將導致所有阻塞操作突然繼續(xù)并在當前線程上設置中斷標志,這通常會導致InterruptedException拋出an 。您可以對此做出反應或檢查Thread.interrupted方法,如果調用該函數的線程的中斷標志已被某人設置(這應該是您在您的情況下創(chuàng)建的線程),則該方法將返回 true 。
進一步閱讀
對于您的情況,FutureTask已被折疊并應使用。它需要一個Executor來運行實際任務。

TA貢獻1784條經驗 獲得超8個贊
如果你能編譯這段代碼,我假設你已經在某處聲明了一個simThread靜態(tài)變量。
顯然,您可以simulate通過不重新聲明來初始化該靜態(tài)變量:
public static void simulate(ActionEvent e){ //Runs the Simulation in a new thread, allowing for realtime updating of the Textarea
Simulate simulation = new Simulate(0.1, Main.house);
simThread = new Thread(simulation.simulate()) {};
simThread.start();
}
但您必須確保:
simulate總是在之前被調用pause,并且
simulate沒有pause中間沒有被調用兩次。
您可以像這樣確保這些條件:
public static synchronized void simulate(ActionEvent e){ //Runs the Simulation in a new thread, allowing for realtime updating of the Textarea
if (simThread != null) {
throw new IllegalStateException("A simulation is already running.");
}
Simulate simulation = new Simulate(0.1, Main.house);
simThread = new Thread(simulation.simulate()) {};
simThread.start();
}
public static synchronized void pause(ActionEvent e){
if (simThread == null) {
throw new IllegalStateException("Simulation is not running.");
}
simThread.interrupt();
simThread = null;
}
添加回答
舉報