|
| 1 | +package com.winterbe.java8.samples.concurrent; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutorService; |
| 4 | +import java.util.concurrent.Executors; |
| 5 | +import java.util.concurrent.TimeUnit; |
| 6 | +import java.util.concurrent.locks.StampedLock; |
| 7 | + |
| 8 | +/** |
| 9 | + * @author Benjamin Winterberg |
| 10 | + */ |
| 11 | +public class Lock4 { |
| 12 | + |
| 13 | + private static int count = 0; |
| 14 | + |
| 15 | + public static void main(String[] args) { |
| 16 | + ExecutorService executor = Executors.newFixedThreadPool(2); |
| 17 | + |
| 18 | + StampedLock lock = new StampedLock(); |
| 19 | + |
| 20 | + executor.submit(() -> { |
| 21 | + long stamp = lock.writeLock(); |
| 22 | + try { |
| 23 | + count++; |
| 24 | + TimeUnit.SECONDS.sleep(1); |
| 25 | + } catch (InterruptedException e) { |
| 26 | + throw new IllegalStateException(e); |
| 27 | + } finally { |
| 28 | + lock.unlockWrite(stamp); |
| 29 | + } |
| 30 | + }); |
| 31 | + |
| 32 | + executor.submit(() -> { |
| 33 | + long stamp = lock.readLock(); |
| 34 | + try { |
| 35 | + System.out.println(Thread.currentThread().getName() + ": " + count); |
| 36 | + TimeUnit.SECONDS.sleep(1); |
| 37 | + } catch (InterruptedException e) { |
| 38 | + throw new IllegalStateException(e); |
| 39 | + } finally { |
| 40 | + lock.unlockRead(stamp); |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + executor.submit(() -> { |
| 45 | + long stamp = lock.readLock(); |
| 46 | + try { |
| 47 | + System.out.println(Thread.currentThread().getName() + ": " + count); |
| 48 | + TimeUnit.SECONDS.sleep(1); |
| 49 | + } catch (InterruptedException e) { |
| 50 | + throw new IllegalStateException(e); |
| 51 | + } finally { |
| 52 | + lock.unlockRead(stamp); |
| 53 | + } |
| 54 | + }); |
| 55 | + |
| 56 | + ConcurrentUtils.stop(executor); |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments