簡體   English   中英

使用ScheduledExecutorService在同一期間運行多個線程

[英]Run more than one thread using ScheduledExecutorService with same period

我可以在我的應用程序中使用多個服務器。 對於每台服務器,我需要在一秒鍾內從服務器中獲取一些信息到解耦的線程中。

如何使用ScheduledExecutorService啟動多個Runnable 我應該為每個線程使用排他的執行器,還是可以使用一個執行器實例並將需要每秒運行的所有可運行對象傳遞給它?

看來您正在尋找的是ScheduledExecutorService#scheduleAtFixedRate()

創建並執行一個周期性操作,該操作將在給定的初始延遲后首先啟用,然后在給定的時間段內啟用; 也就是說執行將在initialDelay initialDelay+periodinitialDelay + 2 * period等之后開始。

這是一個簡單的例子:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(NUMBER_OF_THREADS);
executor.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        // runnable logic           
    }
}, 0, 1, TimeUnit.SECONDS);

您應該在應用程序中使用一個ExecutorService 有關該方法的更多信息,請參見Javadocs。

暫無
暫無

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

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