您的机器人工作人员需要一种共享线程安全的方式来检查工作人员是否应该暂停或播放。在你的 worker 的 run() 方法中,如果线程被暂停,等待这个锁对象的通知。在循环时,或者无论工作人员做什么,定期检查锁的状态,并在需要时暂停工作人员。
pauseIfNeeded() {
synchronized(workerLock) {
if (workerLock.isPaused()) {
workerLock.wait();
}
}
}
您的暂停和播放按钮应该在 workerLock 上获得同步锁,并设置 paused 属性,并在 workerLock 上调用 notify()。这将使工作人员根据需要暂停或继续。无论暂停/播放状态如何,Executor 始终“运行”。
编辑
可以将上面的代码重构为自己的类,如下:
public class WorkerPauseManager {
private boolean paused;
public synchronized void pauseIfNeeded() throws InterruptedException {
if (paused) wait();
}
public synchronized void pause() {
this.paused = true;
}
public synchronized void start() {
this.paused = false;
notifyAll();
}
}
创建 WorkerPauseManager 的单个实例。将此实例传递给您的所有机器人工作人员,并为挥杆暂停/播放动作保留参考以供参考。您的工作线程应该调用 pauseIfNeeded。
这是一个使用 WorkerPauseManager 的 SCCE:
public class WorkerPauseManagerTest {
public static void main(String[] args) {
final WorkerPauseManager pauseManager = new WorkerPauseManager();
new Worker("Worker 1", pauseManager).start();
new Worker("Worker 2", pauseManager).start();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JToggleButton playPauseButton = new JToggleButton(new AbstractAction("Pause") {
public void actionPerformed(final ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
pauseManager.start();
source.setText("Pause");
} else {
pauseManager.pause();
source.setText("Play");
}
}
});
JOptionPane.showMessageDialog(null, playPauseButton, "WorkerPauseManager Demo", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
});
}
private static class Worker extends Thread {
final String name;
final WorkerPauseManager pauseManager;
public Worker(final String name, final WorkerPauseManager pauseManager) {
this.name = name;
this.pauseManager = pauseManager;
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
pauseManager.pauseIfNeeded();
System.out.println(name + " is running");
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}