我无法在中间停止线程。这是我的代码的一部分,在StoplightThread
课堂上我的第一个 if 语句有问题。它应该做的是等待至少 10 秒,然后允许用户按下按钮,以便他们可以改变灯光,如果按下按钮,它应该在这种情况下停止正在运行的线程Thread.sleep(40000)
。发生的情况是,当我按下按钮时,它会改变灯光但不会停止线程。如果我在还剩 20 秒时按下按钮,它将在黄灯的 10 秒上增加 20 秒,使其黄灯持续 30 秒。
编辑:如果你想知道,stoplightCanvas.x == 3
是绿色的,stoplightCanvas.x == 2
是黄色的,stoplightCanvas.x == 1
是红色的。
class StoplightCanvas extends Canvas implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cross) {
isPressed = true;
if (x == 3 && canCross)
x = 2;
}
repaint();
}
}
class StoplightThread extends Thread
{
StoplightCanvas stoplightCanvas;
StoplightThread(StoplightCanvas stoplightCanvas) {
this.stoplightCanvas = stoplightCanvas;
}
public void run()
{
if (stoplightCanvas.x == 3){
Thread.sleep(10000);
stoplightCanvas.canCross = true;
Thread.sleep(40000);
if(stoplightCanvas.isPressed)
StoplightThread.interrupt();
} else if (stoplightCanvas.x == 2) {
Thread.sleep(10000);
} else if (stoplightCanvas.x == 1) {
Thread.sleep(60000);
}
} catch (InterruptedException e){}
stoplightCanvas.toggleColor();
stoplightCanvas.repaint();
}
}
}