java - 使用 ScheduledExecutorService 创建计时器

标签 java multithreading

所以我想弄清楚如何创建一个计时器,我遇到了这个: using ScheduledExecutorService to start and stop timer

他们的示例似乎运行良好。我只是想知道我是否正确使用了它:

  public class TimerTest 
{
  private ScheduledExecutorService  es = null;
  private  boolean timeIsUp = false;
  private ScheduledFuture futureHandler = null;
  private  TimeKeeper timeKeeper = null;
  private  String subject = "";
  private  int siteNo;
  private  long time; 
  private  boolean stop;




public  void endTimer()
{
    System.out.println("we should shutdown everything here");
    es.shutdownNow();
}

public  boolean stopTimer()
{

    if (timeKeeper != null)
    {
        timeKeeper.deactivate();
    }
    futureHandler.cancel(true);
 return true;

}
public  boolean isTimeup()
{
    return timeKeeper.isTimeUp();
}
public void startTimer(long mseconds, String subj, int sNo)
{
    subject = subj;
    siteNo = sNo;
    time = mseconds;
    timeKeeper = new TimeKeeper();
    callScheduler(mseconds);

}

public  boolean isTimerRunning()
{
    return (es.isShutdown() || es == null);

}
public void resetTimer(long t)
 {
    stopTimer();
    callScheduler(t);
 }

public  void resetTimer()
{

   resetTimer(time);  
}

private  void callScheduler(long mseconds)
{
    if (es == null)
        es = Executors.newScheduledThreadPool(3);
    timeKeeper = new TimeKeeper();
    futureHandler = es.schedule( timeKeeper, mseconds, TimeUnit.MILLISECONDS);

}


private class TimeKeeper implements Runnable  {
    //volatile for thread-safety

    private volatile boolean isActive = true;  
    private volatile boolean isTimeUp = false;
    public void run ()   {  
        if (isActive){
            callAlert();
            isTimeUp = true;
        }
    }  
    public void deactivate(){
        isActive = false;
    }

    public boolean isTimeUp()
    {
        return isTimeUp;
    }
    private void callAlert()
    {
        System.out.println("you are in the callAlert method");
    }
  }

 }

这是测试:

 public static void main(String[] args) {
    // TODO Auto-generated method stub
     long pastTime = System.currentTimeMillis();
     TimerTest timer = new TimerTest();
    timer.startTimer(15000, "bh", 1);
    long time;
    int count =0;
    boolean stop = false;
    while(true)
    {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        time = System.currentTimeMillis() - pastTime;

        if (time > 3000)
        {
            if (!stop){
                System.out.println("we are reseting the timer");
                timer.resetTimer(4000);

                timer.stopTimer();
                try {
                    Thread.sleep(3995);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;

            }
            stop = true;


        }
        if (timer.isTimeup())
        {
            System.out.println("our time is up");
            timer.endTimer();
            break;
        }
        if (!stop)
            System.out.println("hello");
        else
        {
            if (count == 0)
                System.out.println("we wait 10 seconds from now");
            count++;
        }


    }
    timer.resetTimer(1200);
    while (true)
    {
        if (timer.isTimeup())
        {
            timer.isTimeup();
            System.out.println("breaking after time is up");
            break;
        }
    }
    timer.endTimer();

}

这似乎可行,我可能错过了一些我需要的东西,这是我第一次使用 ScheduledExecutorService 你们看到这段代码有什么问题吗? 我不希望与线程冲突发生冲突。

最佳答案

ScheduledExecutorService您会自动获得计时器功能。除非您有 ScheduleExecutorService 不能提供的东西,否则您不需要它。 例如假设您想在初始延迟 10 秒后开始任务,随后每次延迟 5 秒。

public void init() {
    executor = new ScheduledThreadPoolExecutor(corePoolSize);
    executor.scheduleWithFixedDelay(new WorkerThread(), 10, 5, TimeUnit.SECONDS);
}

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

关于java - 使用 ScheduledExecutorService 创建计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13024787/

相关文章:

java - 我如何测量有多少线程正在执行一段代码?

java - 二叉搜索树对象创建问题

java - BufferedReader Java ,替换 CSV 文件中的所有匹配项

multithreading - 核心数据保存竞争条件错误

java - StreamCorruptedException : invalid type code: AC

java - Java 队列的多线程处理

java - 线程上可运行对象的受监督调用

java - 循环遍历方向

java - 给定一个数字 n ,我们必须找出小于或等于 n 且恰好有 3 个约数的数字

java - 无法在板上使用 stock android 读取 cubieboard 上的串行数据