从纯线程管理的角度来看,我认为最干净的方法是使用执行器。这并不能解决您的克隆(或不克隆)问题。
创建一个保存游戏的方法:
public void saveTheGame() {
//you maybe need to take a snapshot, which might require synchronization
GameState state = ....;
}
创建一个可运行的,例如作为类实例成员,嵌入该调用和执行程序服务:
private final Runnable save = new Runnable() {
public void run() {
saveTheGame();
}
}
private final ExecutorService executor = Executors.newFixedThreadPool(1);
并在需要时保存游戏:
executor.submit(save);
关闭应用程序时不要忘记关闭执行程序:
executor.shutdown();
例如,您也可以使用ScheduledExecutorService
每 x 分钟运行一次的代替。
例如,该类可能如下所示:
public static class GameSaver {
private final Runnable save = new Runnable() {
@Override
public void run() {
saveGame();
}
};
private static final ExecutorService executor = Executors.newFixedThreadPool(1);
private final GameState state;
public GameSaver(GameState state) {
this.state = state;
}
public void save() {
executor.submit(save);
}
public static void close() {
executor.shutdown();
}
private void saveGame() {
//save your game here
}
}
并在您的主要代码中:
GameState state = getGameState();
GameSaver saver = new GameSaver(state);
saver.save();