怎么控制同一时间只有3个线程运行?
直接上代码
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;public class SemaphoreThreadPoolExample {private static final int THREAD_COUNT = 10;private static final int MAX_CONCURRENT_THREADS = 3;public static void main(String[] args) {// 创建了一个固定大小为10的线程池ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);// 初始化一个信号量 semaphore,设置最大并发线程数为3Semaphore semaphore = new Semaphore(MAX_CONCURRENT_THREADS);// 创建10个线程任务for (int i = 0; i < THREAD_COUNT; i++) {Runnable task = new Task(semaphore);executor.execute(task);}executor.shutdown();}static class Task implements Runnable {private final Semaphore semaphore;public Task(Semaphore semaphore) {this.semaphore = semaphore;}@Overridepublic void run() {try {semaphore.acquire(); // 获取许可System.out.println(new Date() + "Thread " + Thread.currentThread().getId() + " is running.");// 暂停一会Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();} finally {semaphore.release(); // 释放许可}}}
}
看一下执行结果
每次只有三个线程在执行