簡體   English   中英

在Java 8中使用無限循環生成Thread的最佳方法是什么?

[英]What is the best way to spawn a Thread with an infinite loop in Java 8?

我有一個方法需要每n秒調用一次。 在Java的舊時代,我會做這樣的事情:

Runnable task = () -> {

  while (!updater.isInterrupted()) {
       //some Task
    } catch (InterruptedException e) {}
   }
};
Thread updater = new Thread(task);
updater.start();

}

但這顯然是一個壞主意。 如果我想停止Thread,我需要調用updater.interrupt()並依賴異常處理,這實際上並不是針對這些東西做的。

所以我想有一些奇特的“新”Java8方式。我看到了這個:

public class TestSchedularService {
 long sleep = 500;

 @Test
 public void testLoop2() throws Exception {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture future = executor.scheduleWithFixedDelay(new PollingService(), 0, sleep,TimeUnit.MILLISECONDS);
Thread.sleep(2 * sleep);
future.cancel(false);
executor.shutdown();
 }
}

class PollingService implements Runnable {
 private int count = 0;
public void run() {
System.out.println("iteration :" + (count++));
 }
}

但似乎它正在每次調用時創建一個PollingService實例,這看起來很糟糕。 那么每n秒調用一個方法最有效和“最新”的方法是什么?

使用ScheduledExecutorService是正確的方法。 它不會創建PollingService新實例,您創建它並且執行程序調用始終在同一實例上run ,直到您取消Future

暫無
暫無

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

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