【虚拟线程】java21虚拟线程用法 限流等
java
//创建虚拟线程工厂
ThreadFactory virtualThreadFactory = Thread.ofVirtual()
.name("虚拟线程-", 0)
.factory();
//每次最多只能执行10个
Semaphore 限流 = new Semaphore(10);
List<Thread> threads = new ArrayList<>();
for(int i = 1; i <= 100; i++){
Runnable runnable = () -> {
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();
}
}