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