工作中用到了線程池和調度線程相關的知識,記錄一下
@Test
public void testThreadPool() throws InterruptedException {
// 錯誤的創建線程池的方式
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// scheduleWithFixedDelay:執行完第一次任務後間隔1秒執行下一次任務
scheduledExecutorService.scheduleWithFixedDelay(() -> {
System.out.println("scheduleWithFixedDelay...");
}, 1, 1, TimeUnit.SECONDS);
// scheduleAtFixedRate:每1秒執行一次任務,即使上一個任務沒有完成
scheduledExecutorService.scheduleAtFixedRate(() -> {
System.out.println("scheduleAtFixedRate...");
}, 1, 1, TimeUnit.SECONDS);
// 定義主線程休眠,否則調度線程在主線程結束後無法正常執行
Thread.sleep(1000000000L);
}
@Test
public void testThreadPool() throws InterruptedException {
// 正確的創建線程池的方式(可自定義線程名稱,方便排查問題)
ThreadFactory factory =
new ThreadFactoryBuilder().setNameFormat("thread-name-%d").build();
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, factory,
new ScheduledThreadPoolExecutor.AbortPolicy());
// scheduleWithFixedDelay:執行完第一次任務後間隔1秒執行下一次任務
scheduledExecutorService.scheduleWithFixedDelay(() -> {
System.out.println("scheduleWithFixedDelay...");
}, 1, 1, TimeUnit.SECONDS);
// scheduleAtFixedRate:每1秒執行一次任務,即使上一個任務沒有完成
scheduledExecutorService.scheduleAtFixedRate(() -> {
System.out.println("scheduleAtFixedRate...");
}, 1, 1, TimeUnit.SECONDS);
// 定義主線程休眠,否則調度線程在主線程結束後無法正常執行
Thread.sleep(1000000000L);
}
阿里編碼規約也禁止使用Executors或者顯式創建線程(池),這是優化後的方案