Semaphore
控制对资源的并发访问数,构造时如果传参为1,则近似于ReentrantLock,差别在于锁的释放。可以一个线程获取锁,另外一个线程释放锁,在一些死锁处理的场合比较适用。
如上所示,信号量为4,当超过4个并发试图访问共享资源时,多出来的线程(红色部分)会被阻塞,直至有线程释放信号量。
使用示例如下:
1 @Test 2 public void test1() { 3 final Semaphore semaphore = new Semaphore(2); 4 ExecutorService executorService = Executors.newCachedThreadPool(); 5 6 final AtomicInteger executeNums = new AtomicInteger(); 7 for(int num = 0; num < 20; num++) { 8 executorService.execute(new Runnable() { 9 @Override 10 public void run() { 11 try { 12 semaphore.acquire(); 13 System.err.println("thread-" + Thread.currentThread().getId()); 14 Thread.sleep(1000); 15 executeNums.incrementAndGet(); 16 semaphore.release(); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 }); 22 } 23 24 while (executeNums.get() < 20) { 25 try { 26 Thread.sleep(1000); 27 } catch (InterruptedException e) { 28 e.printStackTrace(); 29 } 30 } 31 executorService.shutdown(); 32 }