几种线程池特点

  1. 普通线程池发生异常,会自动创建新的线程填补异常毁掉的线程
  2. ScheduledExecutorService按照固定频率、按照固定延迟发生异常,就会waiting住,导致无法继续执行,所以需要catch异常,不能抛出异常
  3. 按照固定频率执行,如果任务执行时间超过频率时间,那么会连续执行,而按照固定延迟执行,无论执行多久,都会间隔指定时间执行
@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);
        }
    }
}

posted @ 2024-02-24 17:54  神一样的存在  阅读(5)  评论(0编辑  收藏  举报