0
点赞
收藏
分享

微信扫一扫

【虚拟线程】java21虚拟线程用法 限流等


【虚拟线程】java21虚拟线程用法 限流等

//创建虚拟线程工厂
ThreadFactory virtualThreadFactory = Thread.ofVirtual()
        .name("虚拟线程-", 0)
        .factory();


//每次最多只能执行10个
Semaphore 限流 = new Semaphore(10);

List<Thread> threads = new ArrayList<>();

for(int i = 0; i < 100; i++){

    Runnable runnable = () -> {
    
        //TODO 这里写业务逻辑
    
        ThreadUtil.sleep(1000 * 5);
        //释放许可,以供其他线程使用
        限流.release();
     };


    Thread factoryThread = virtualThreadFactory.newThread(runnable);

    //申请许可,如果当前没有许可了,则阻塞直至其他线程 release 以释放
    限流.acquire();
    //开始
    factoryThread.start();
    threads.add(factoryThread);
}

//等待都执行完成
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

方案二

//创建虚拟线程工厂
        ThreadFactory virtualThreadFactory = Thread.ofVirtual()
                .name("虚拟线程-", 0)
                .factory();
        
//线程池   引用com.alibaba.ttl.threadpool
        return TtlExecutors.getTtlExecutorService(new ThreadPoolExecutor(核心数量, 最大数量, 60,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueCapacity), virtualThreadFactory, new ThreadPoolExecutor.AbortPolicy()));

方案三

ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();

举报

相关推荐

0 条评论