Semaphore(信号量)是用来控制同时访问特定资源的线程数量,它通过协调各个线程,以保证合理的使用公共资源。
代码示例:
1 class SemaphoreTest{ 2 private static final int THREAD_COUNT = 30; 3 private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); 4 private static Semaphore semaphore = new Semaphore(10); 5 public static void main(String[] args){ 6 for (int i = 0; i < THREAD_COUNT; i++){ 7 threadPool.execute(new Runnable() { 8 @Override 9 public void run() { 10 try { 11 semaphore.acquire(); 12 System.out.println(Thread.currentThread() + ":Save data"); 13 semaphore.release(); 14 }catch (InterruptedException e){ 15 16 } 17 } 18 }); 19 } 20 threadPool.shutdown(); 21 } 22 }
代码中,虽然有30个线程在执行,但是只允许10个并发执行。