hooyantsing's Blog

8_Lock版的生产者消程

字数统计: 324阅读时长: 1 min
2020/08/24

8 Lock版的生产者消程

狂神说Java JUC并发编程最新版通俗易懂

synchronized 替换成 Lock

b129e63b41cc4a85539f32f75fca8141.png

JDK 手册说明使用方式:

f141aadad94bb32938a461f72774be86.png

案例

生产者消费者 Lock版。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package demo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {
public static void main(String[] args) {
Date2 date = new Date2();
new Thread(
() -> {
try {
for (int i = 0; i < 10; i++) {
date.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A"
).start();

new Thread(
() -> {
try {
for (int i = 0; i < 10; i++) {
date.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B"
).start();

new Thread(
() -> {
try {
for (int i = 0; i < 10; i++) {
date.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C"
).start();

new Thread(
() -> {
try {
for (int i = 0; i < 10; i++) {
date.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"D"
).start();
}
}

class Date2 {
private int number = 1;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();

public void increment() throws InterruptedException {
lock.lock();
try {
while (number != 0){
condition.await();
}
number++;
System.out.println("生产者" + Thread.currentThread().getName() + "-->" + number);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void decrement() throws InterruptedException {
lock.lock();
try {
while (number == 0){
condition.await();
}
number--;
System.out.println("消费者" + Thread.currentThread().getName() + "-->" + number);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
CATALOG
  1. 1. 8 Lock版的生产者消程
    1. 1.0.1. synchronized 替换成 Lock
    2. 1.0.2. 案例