如何用Java暂停/重启SingleThreadExecutor(ExecutorService)?

时间:2016-02-13 07:53:15

标签: java multithreading concurrency java.util.concurrent

我已经实现了一个Singleton类“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();
    }
}

1 个答案:

答案 0 :(得分:0)

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

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();
}