- 普通線程池發生異常,會自動創建新的線程填補異常毀掉的線程
- ScheduledExecutorService按照固定頻率、按照固定延遲發生異常,就會waiting住,導致無法繼續執行,所以需要catch異常,不能拋出異常
- 按照固定頻率執行,如果任務執行時間超過頻率時間,那麼會連續執行,而按照固定延遲執行,無論執行多久,都會間隔指定時間執行
@Slf4j
class BaseTest {
private static final ScheduledExecutorService POOL = new ScheduledThreadPoolExecutor(1, r -> {
Thread t = new Thread(r);
t.setName("E-POOL");
return t;
});
@Test
void rateTest() throws Exception {
AtomicInteger count = new AtomicInteger();
POOL.scheduleAtFixedRate(() -> {
System.err.println(123);
int data = count.incrementAndGet();
try {
if (data >= 5) {
throw new RuntimeException("123");
}
} catch (Exception e) {
log.error(Throwables.getStackTraceAsString(e));
}
}, 1L, 1L, TimeUnit.SECONDS);
SECONDS.sleep(Long.MAX_VALUE);
}
@Test
void delayTest() throws Exception {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("my-test-pool-%d").build();
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, threadFactory);
Date startTime = new Date();
System.out.println("startTime: " + startTime.toString());
scheduledExecutorService.scheduleAtFixedRate(() -> {
System.out.println("beginTime: " + new Date().toString());
try {
Thread.sleep(5 * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("endTime: " + new Date().toString());
}, 2, 3, TimeUnit.SECONDS);
SECONDS.sleep(Long.MAX_VALUE);
}
@Test
void commonTest() throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
while (true) {
pool.execute(() -> {
// 觀察現成id是否在變化
System.err.println(Thread.currentThread().getId());
throw new RuntimeException();
});
SECONDS.sleep(1L);
}
}
}