我再次遇到過這樣的情況:只能停止/銷燬/暫停線程。 .interrupt()不會執行此操作,不推薦使用.stop()和.suspend()。爲什麼在Java中停止線程很困難?
很簡單的例子:
public class TimerThread extends Thread {
private JPanel colorPanel;
public TimerThread(JPanel colorPanel) {
this.colorPanel = colorPanel;
}
public void run() {
while (true) {
try {
Thread.sleep(1000);
colorPanel.repaint();
} catch (Exception ex) {
//do Nothing
}
}
}
}
這樣做是什麼重繪一定的JPanel每秒改變其顏色。我要開始從另一個類停止線程像這樣:(?)
timer = new Thread(new TimerThread(colorPanel));
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.interrupt();
}
});
顯然,這並不工作...我知道我可以用一個定時器,一個SwingWorker的或聲明的計時器爲timer = new TimerThread(colorPanel);
和在run方法中使用布爾值而不是「true」,但我被要求將計時器聲明爲「線程」,而不是別的。
讓我驚訝的(或這是愚蠢的?),即使這並不工作:
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer = new Thread(new TimerThread(colorPanel));
timer.start();
}
});
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.interrupt();
timer = null;
}
});
所以我的問題很簡單:你如何使線程開始/暫停/恢復/停止在Java中?
如果您仍然遇到這種情況,您需要重新考慮如何使用線程。線程應該控制自己的生命週期,而不是在外部暫停/停止。這是一個設計問題。 – skaffman
@skaffman再次閱讀OP:這是作業,他只能使用一個線程。 – toto2
確實@total2,它可能是多麼不幸,如果更高階的命令你使用線程你不能提供的東西,與SwingWorker實現... – Matthias