-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLThreadDemo.java
More file actions
107 lines (90 loc) · 2.68 KB
/
Copy pathLThreadDemo.java
File metadata and controls
107 lines (90 loc) · 2.68 KB
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
97
98
99
100
101
102
103
104
105
106
107
package lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author : CodeWater
* @create :2022-06-02-20:34
* @Function Description :线程间的通信: +1 和-1动作交替进行
* -------------------------使用lock实现-----------------
*/
//第一步 创建资源类,定义属性和操作方法
class Share{
private int number = 0;
//创建Lock
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//+1
public void incr() throws InterruptedException {
//上锁
lock.lock();
try{
//判断 只有等于0才能通过
while( number != 0 ){
condition.await();
}
//干活
number++;
System.out.println( Thread.currentThread().getName() + ":: " + number );
//通知
condition.signalAll();
}finally{
lock.unlock();
}
}
//-1
public void decr() throws InterruptedException {
lock.lock();
try{
while( number != 1 ){
condition.await();
}
number--;
System.out.println( Thread.currentThread().getName() + "::" + number );
condition.signalAll();
}finally{
lock.unlock();
}
}
}
public class LThreadDemo {
public static void main(String[] args ) {
Share share = new Share();
new Thread( () -> {
for( int i = 0 ; i < 10 ; i++ ){
try{
share.incr();
}catch ( InterruptedException e ){
e.printStackTrace();
}
}
} , "AA" ).start();
new Thread( () -> {
for( int i = 0 ; i < 10 ; i++ ){
try{
share.decr();
}catch ( InterruptedException e ){
e.printStackTrace();
}
}
} , "BB" ).start();
new Thread( () -> {
for( int i = 0 ; i < 10 ; i++ ){
try{
share.incr();
}catch ( InterruptedException e ){
e.printStackTrace();
}
}
} , "CC" ).start();
new Thread( () -> {
for( int i = 0 ; i < 10 ; i++ ){
try{
share.decr();
}catch ( InterruptedException e ){
e.printStackTrace();
}
}
} , "DD" ).start();
}
}