有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用ExecutorService在特定任务完成后重新运行

我正在尝试创建一个模块,它将提交一个CallableExecutorService并等待响应。如果可调用函数返回null,这个线程将暂停自己,直到调用resume()。否则它将处理结果并再次提交相同的任务

public class ScheduleManager implements Runnable {

    private ExecutorService executor = Executors.newSingleThreadExecutor();

    @Override
    public synchronized void run() {
        while (true) {
            Future<Schedule> future = executor.submit(new ScheduleRetriever());

            try {
                Schedule schedule = future.get();

                if (schedule == null) {
                    this.wait();
                } else {
                    //Do something with the schedule
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void resume() {
        this.notifyAll();
    }
}

我设法想出了上述解决方案,但我不确定它是否可靠

有没有办法做得更好


共 (0) 个答案