如何暂停newScheduledThreadPool?

时间:2017-12-11 08:57:56

标签: java javafx

我正在做一个应用程序java和场景构建器,我会创建一个newScheduledThreadPool(1)。当我点击按钮时,当我再次点击按钮时,执行者必须暂停,当我再次单击按钮时,执行者将恢复他的工作。

这是我的代码:

public  class  ExecutorThreadReadDatabase {
static Logger logger = MyLog4J.getInstance();
private static boolean stopThread ;
private static ExecutorThreadReadDatabase executorThreadReadDatabase;
private ScheduledExecutorService executor;
public ExecutorThreadReadDatabase() {
    executor = Executors.newScheduledThreadPool(1);
}
public  static ExecutorThreadReadDatabase getInstance() {
    if (executorThreadReadDatabase == null) {
        logger.info("null");    
        return new ExecutorThreadReadDatabase();
    } else {
        logger.info("not nullo");
        return executorThreadReadDatabase;
    }
    }

public  void readToDatabaseFromNetworkServer() {
    logger.info("lo stop è : "+stopThread);
    executor.scheduleAtFixedRate(RunnableThread.getInstance(), 0, 5, 
TimeUnit.SECONDS);
}
public void stopT() {
    logger.info("stoppo l' executor");
    executor.shutdown();
    executor.wait()
}

抱歉我的英文不好

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是保持"暂停"在ExecutorThreadReadDatabase中标记,并将您提交的Runnable包装到另一个Runnable中的执行程序中,在运行之前检查暂停标志的值:

public  class  ExecutorThreadReadDatabase {
  private volatile boolean paused = false;

  // ...

  public  void readToDatabaseFromNetworkServer() {
    logger.info("lo stop è : "+stopThread);

    RunnableThread rt = RunnableThread.getInstance();
    Runnable r = new Runnable() {
      @Override public void run() {
        if (paused) return;
        rt.run();
      }
    };

    executor.scheduleAtFixedRate(r, 0, 5, TimeUnit.SECONDS);
}