多线程对于可以在java中暂停和取消暂停的线程化应用程序,有一个好的解决方案吗?
我很难找到一个好方法来编写一个在自己线程上运行的应用程序。人们应该能够启动和停止它,并在它运行时暂停和取消暂停
public abstract class Application implements Runnable {
private Thread runningThread;
private volatile boolean isRunning;
private volatile boolean isPaused;
public Application() {
serverThread = null;
isRunning = false;
isPaused = false;
}
public synchronized void start() {
if(!isRunning) {
isRunning = true;
serverThread = new Thread(this);
serverThread.start();
}
}
public synchronized void stop() {
if(isRunning) {
isRunning = false;
try {
serverThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void pause() {
if(isRunning && !isPaused) {
isPaused = true;
}
}
public synchronized void unpause() {
if(isRunning && isPaused) {
isPaused = false;
}
}
protected abstract void setUp();
protected abstract void update();
protected abstract void cleanUp();
@Override
public void run() {
setUp();
while(isRunning) {
if(!isPaused) {
update();
}
}
cleanUp();
}
}
最糟糕的是,很难正确地调试运行在不同线程上的程序
# 1 楼答案
使用IntelliJ或Eclipse之类的调试器,它们具有设置断点的内置功能,然后在检查变量等时暂停应用程序的执行