[英]Using ScheduledExecutorService, How to Start a Thread without waiting for other thread to complete at fixed interval?
[英]How to run a fixed interval thread from start of app?
這可能是措辭不佳的標題,但是我試圖從一開始就收集有關我的應用程序的數據和統計信息。 我正在使用JavaFX,並且有一個模型類將處理所有數據和處理。
我想要的是該模型類從應用程序啟動開始就開始收集數據(例如運行時,線程計數,內存使用...)。 但是我還希望它每秒更新一次這些值,這意味着我需要它在某種ScheduledExecutorThread之類的程序上運行。
我該怎么做,以便從該程序的開始,模型類便每秒運行一次“ update()”函數?
每當您要使用Java進行固定間隔操作時,都應該調查ScheduledExecutorService 。 就您而言,類似:
private static final ScheduledExecutorService SERVICE = Executors.newScheduledThreadPool(1,
new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread("Tick Thread", r);
t.setDaemon(true);
return t;
}
});
private static final AtomicReference<Controller> CONTROLLER = new AtomicReference<>();
public static final void setController(Controller c) {
CONTROLLER.compareAndSet(null, c);
}
static {
Runnable task = new Runnable() {
public void run() {
//do something each second....
// call the 'update()' method:
Controller c = CONTROLLER.get();
if (c != null) {
c.update();
}
}
}
// delay 1 second, repeat each second.
service.scheduleAtFixedRate(task, 1, 1, TimeUnit.SECONDS);
}
您可以將其放入類的靜態初始化器中,並在加載類后立即啟動系統...。您可能希望ExecutorService上的線程成為Daemon主題。所以你需要一個自定義線程工廠。
上面的代碼將立即啟動,並將每秒更新一次Controller(如果有)。
創建c控制器后,就可以使用靜態方法設置該值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.