gpt4 book ai didi

java - 如何在Java中暂停/重新启动SingleThreadExecutor(ExecutorService)?

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:04 28 4
gpt4 key购买 nike

我已经实现了一个单例类“SingleTaskExecutor”,它使用 SingleThreadExecutor 一次按顺序执行一个任务。该类用于按顺序一次执行一个异步数据库操作。一切正常。然而现在我们有一个用例,我们需要暂停该服务一段时间,执行一些操作,然后恢复服务。不确定如何暂停/恢复服务。这是我的代码:

public class SingleTaskExecutor {

private SingleTaskExecutor() {}
private final ExecutorService executor = Executors.newSingleThreadExecutor();

private static class LazyHolder {
private static final SingleTaskExecutor instance = new SingleTaskExecutor();
}

public static SingleTaskExecutor getInstance() {
return LazyHolder.instance;
}

public <T> Task<T> create(Callable<T> callable) {
Task<T> task = new Task<T>() {
@Override
protected T call() throws Exception {
return callable.call();
}
};
return task;
}

public <T> T execute(Task<T> task) {
return (T) executor.submit(task);
}

public void shutDown() {
executor.shutdown();
}

public void awaitTermination() {
try {
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void waitPlease() {
try {
Thread.currentThread().wait();
//executor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void resume() {
Thread.currentThread().notifyAll();
//executor.notifyAll();
}
}

最佳答案

如果我理解正确的话,您想要暂停任务的执行,然后执行一些显式任务,然后恢复它。我实际上看到了以下解决方案:

private volatile boolean paused;

public <T> T execute(Task<T> task) {
if(paused) {
synchronized(this) {
if(paused) {
wait();
}
}
}
return (T) executor.submit(task);
}

public synchronized void waitPlease() {
paused = true;
}

public synchronized void resume() {
paused = false;
notify();
}

关于java - 如何在Java中暂停/重新启动SingleThreadExecutor(ExecutorService)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35377481/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com