2015-09-24 58 views
0

是否有可能使ScheduledExecutorService有一個正在運行的任務並且只有一個等待任務?ScheduledExecutorService和計劃的行爲

Runnable runnable; 
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 
    private volatile ScheduledFuture<?> self; 

protected void waitAndSweep(final String symbol) { 
    try { 

     runnable = new Runnable() { 
      @Override 
      public void run() { 
      try { 
       long sweepTime = symbolInfo.getSweepTime(symbol); 
       long timeSinceLastSweep = System.currentTimeMillis() - sweepTime; 
       long waitTime = timeSinceLastSweep >= getInterval() ? 0 : getInterval() - timeSinceLastSweep; 
       logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime); 
       if (waitTime > 0){ 
       Thread.sleep(waitTime); 
       } 
       callSweep(symbol); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }    
      } 
     }; 

     self = scheduler.schedule(runnable,0,TimeUnit.SECONDS); 


    }catch (Exception e) { 
     logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol, 
      "Exception caught...", e); 
    } 
    } 

在上面的代碼中,假定一個可運行的任務是通過調度計劃,並等待10秒(Thread.sleep代碼(時間)),在這個睡眠時間,如果有通過調度它會安排一些其他任務等待。現在第三個任務進入調度程序,然後調度程序不應該接受它,因爲已經有一個運行和一個等待任務

回答

0

您是否需要使用ScheduledExecutorService或將ThreadPoolExecutor做什麼?如果是這樣,你能控制多少任務可以通過創建這個自己(而不是使用Executors.newFixedThreadPool(1)),並提供自己的隊列中定義的能力,像這樣在一次排隊:

int oneThread  = 1; 
    long zeroKeepAlive = 0L; 
    int queueDepthOfOne = 1; 

    ThreadPoolExecutor threadPoolExecutor = 
     new ThreadPoolExecutor(
       oneThread, 
       oneThread, 
       zeroKeepAlive, 
       TimeUnit.MILLISECONDS, 
       new ArrayBlockingQueue<Runnable>(queueDepthOfOne) 
     ); 

ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); 
threadPoolTaskExecutor.setQueueCapacity(1); 

ThreadPoolTask​​Executor類的API文檔:另外,您可以通過使用Spring框架的ThreadPoolTask​​Executor類類少一些配置做http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.html

+0

此隊列是抱着等待任務或兩者兼有跑和等待任務? – user5367186

+0

隊列只保存等待任務。 – Nate

+0

是否有的ThreadPoolExecutor的ThreadPoolExecutor = 新的ThreadPoolExecutor任何工廠方法( oneThread, oneThread, zeroKeepAlive, TimeUnit.MILLISECONDS, 新ArrayBlockingQueue (queueDepthOfOne) ); – user5367186

相關問題