簡體   English   中英

使用ScheduledExecutorService創建計時器

[英]Creating a timer with ScheduledExecutorService

所以我想弄清楚如何創建一個計時器,我遇到了這個: 使用ScheduledExecutorService來啟動和停止計時器

他們的例子看起來效果很好。 我只是想知道我是否正確使用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM