diff --git a/src/UpdateThread.java b/src/UpdateThread.java new file mode 100644 index 0000000..7a434c3 --- /dev/null +++ b/src/UpdateThread.java @@ -0,0 +1,39 @@ +package cn.edu.caztc.sokobangame; + +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class UpdateThread extends Thread { + private final JPanel panel; + private volatile boolean running = true; // 控制线程运行的标志 + + public UpdateThread(JPanel panel) { + this.panel = panel; + setDaemon(true); // 设为守护线程,避免阻止JVM退出 + } + + // 添加 stopRunning() 方法,用于安全停止线程 + public void stopRunning() { + running = false; // 设置标志位 + interrupt(); // 中断线程(如果它在 sleep/wait 状态) + } + + @Override + public void run() { + while (running) { + try { + SwingUtilities.invokeLater(() -> { + if (panel != null) { + panel.repaint(); + } + }); + Thread.sleep(50); + } catch (InterruptedException e) { + System.out.println("更新线程被中断"); // 添加线程中断信息 + Thread.currentThread().interrupt(); + break; + } + } + System.out.println("更新线程已停止"); // 添加线程停止信息 + } +} \ No newline at end of file