|
| 1 | +package com.winterbe.java8.samples.concurrent; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.Executors; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | +import java.util.concurrent.locks.ReadWriteLock; |
| 9 | +import java.util.concurrent.locks.ReentrantReadWriteLock; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author Benjamin Winterberg |
| 13 | + */ |
| 14 | +public class Lock3 { |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + ExecutorService executor = Executors.newFixedThreadPool(2); |
| 18 | + |
| 19 | + Map<String, String> map = new HashMap<>(); |
| 20 | + |
| 21 | + ReadWriteLock lock = new ReentrantReadWriteLock(); |
| 22 | + |
| 23 | + executor.submit(() -> { |
| 24 | + lock.writeLock().lock(); |
| 25 | + try { |
| 26 | + TimeUnit.SECONDS.sleep(1); |
| 27 | + map.put("foo", "bar"); |
| 28 | + } |
| 29 | + catch (InterruptedException e) { |
| 30 | + throw new IllegalStateException(e); |
| 31 | + } |
| 32 | + finally { |
| 33 | + lock.writeLock().unlock(); |
| 34 | + } |
| 35 | + }); |
| 36 | + |
| 37 | + executor.submit(() -> { |
| 38 | + lock.readLock().lock(); |
| 39 | + try { |
| 40 | + String foo = map.get("foo"); |
| 41 | + System.out.println(foo); |
| 42 | + TimeUnit.SECONDS.sleep(1); |
| 43 | + } |
| 44 | + catch (InterruptedException e) { |
| 45 | + throw new IllegalStateException(e); |
| 46 | + } |
| 47 | + finally { |
| 48 | + lock.readLock().unlock(); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + executor.submit(() -> { |
| 53 | + lock.readLock().lock(); |
| 54 | + try { |
| 55 | + String foo = map.get("foo"); |
| 56 | + System.out.println(foo); |
| 57 | + TimeUnit.SECONDS.sleep(1); |
| 58 | + } |
| 59 | + catch (InterruptedException e) { |
| 60 | + throw new IllegalStateException(e); |
| 61 | + } |
| 62 | + finally { |
| 63 | + lock.readLock().unlock(); |
| 64 | + } |
| 65 | + }); |
| 66 | + |
| 67 | + ConcurrentUtils.stop(executor); |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments