暂停SwingWorker
我是GUI和multithreading的初学者。 我目前有一个模拟,它运行在控制台中移动的bug。 我希望能够使用按钮暂停错误。 我有两个按钮(运行和暂停)运行按钮将启动模拟,暂停按钮应暂停它(或让它睡一会儿)我设法让运行按钮工作但我无法点击暂停一旦它跑步(因为它在我认为的同一个线程中)我已经读了很多但似乎仍然无法解决它…任何帮助都会被大量赞赏.. //在我的行动听众..
else if (E.getSource() == Pause) { Worker pauseWorker = new Worker(); pauseWorker.execute();
在我的新工人阶级
import javax.swing.SwingWorker; public class Worker extends SwingWorker { @Override protected Void doInBackground() throws Exception { // System.out.println("Background"); for (int i = 0; i <= 1; i++) { Thread.sleep(1000); System.out.println("Background running"); } return null; }
}
else if (E.getSource() == Pause) { Worker pauseWorker = new Worker(); pauseWorker.execute();
这会启动一个新工人,不会停止正在运行的工人。
相反,您可以保留对后台工作程序的引用,并在按下暂停按钮时cancel()
它cancel()
。 请参阅SwingWorker.cancel()
else if (E.getSource() == Pause) { worker.cancel(true); }
在工人阶级,定期检查您是否被取消:
@Override protected Void doInBackground() throws Exception { // System.out.println("Background"); while(!isCancelled()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { System.out.println("Background interrupted"); } System.out.println("Background running"); } return null; }
如果您确实需要暂停而不是取消该工作程序,则必须编写自己的pause()方法并自行执行管理。
为了给你一些想法,这样的东西会进入工人类:
boolean paused = false; public void pause() { paused = true; } public synchronized void resume() { paused = false; this.notify(); } @Override protected Void doInBackground() throws Exception { while(!isCancelled()) { if( paused ) { System.out.println("Background paused, waiting for resume"); try { synchronized(this){ wait(1000); } } catch (InterruptedException ex) { System.out.println("Background interrupted"); } } else { System.out.println("Background running"); // do a chunk of actual work } } return null; }