|
| 1 | +packagecom.winterbe.java8.samples.concurrent; |
| 2 | + |
| 3 | +importjava.util.concurrent.ExecutorService; |
| 4 | +importjava.util.concurrent.Executors; |
| 5 | +importjava.util.concurrent.Semaphore; |
| 6 | +importjava.util.concurrent.TimeUnit; |
| 7 | +importjava.util.stream.IntStream; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author Benjamin Winterberg |
| 11 | + */ |
| 12 | +publicclassSemaphore2 { |
| 13 | + |
| 14 | +privatestaticSemaphoresemaphore =newSemaphore(5); |
| 15 | + |
| 16 | +publicstaticvoidmain(String[]args) { |
| 17 | +ExecutorServiceexecutor =Executors.newFixedThreadPool(10); |
| 18 | + |
| 19 | +IntStream.range(0,10) |
| 20 | + .forEach(i ->executor.submit(Semaphore2::doWork)); |
| 21 | + |
| 22 | +ConcurrentUtils.stop(executor); |
| 23 | + } |
| 24 | + |
| 25 | +privatestaticvoiddoWork() { |
| 26 | +booleanpermit =false; |
| 27 | +try { |
| 28 | +permit =semaphore.tryAcquire(1,TimeUnit.SECONDS); |
| 29 | +if (permit) { |
| 30 | +System.out.println("Semaphore acquired"); |
| 31 | +ConcurrentUtils.sleep(5); |
| 32 | + }else { |
| 33 | +System.out.println("Could not acquire semaphore"); |
| 34 | + } |
| 35 | + }catch (InterruptedExceptione) { |
| 36 | +thrownewIllegalStateException(e); |
| 37 | + }finally { |
| 38 | +if (permit) { |
| 39 | +semaphore.release(); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | +} |