-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLThreadDemo2.java
More file actions
125 lines (111 loc) · 3.45 KB
/
Copy pathLThreadDemo2.java
File metadata and controls
125 lines (111 loc) · 3.45 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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:53
* @Function Description :线程键定制化通信: 让线程按照指定顺序运行
* 线程A先打印5次------B打印10次-------------C打印15次
* 轮数有输入决定
*/
//第一步 创建资源类
class ShareResource{
//定义标志位 1AA 2BB 3CC
private int flag = 1 ;
//创建Lock锁
private Lock lock = new ReentrantLock();
//创建三个condition
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
//打印5次,参数第几轮
public void print5( int loop ) throws InterruptedException {
//上锁
lock.lock();
try{
//判断
while( flag != 1 ){
//等待
c1.await();
}
//干活
for( int i = 0 ; i < 5 ; i++ ){
System.out.println( Thread.currentThread().getName() + "::" + i + ":轮数: " + loop );
}
//通知
flag = 2 ;//修改标志位 2
c2.signal();//通知BB线程
}finally{
//释放锁
lock.unlock();
}
}
//打印10次,参数第几轮
public void print10( int loop ) throws InterruptedException {
lock.lock();
try{
while( flag != 2 ){
c2.await();
}
for( int i = 0 ; i < 10 ; i++ ){
System.out.println( Thread.currentThread().getName() + "::" + i + ":轮数:" + loop );
}
//修改标志位
flag = 3;
c3.signal();//通知CC线程
}finally{
lock.unlock();
}
}
//打印15次,参数第几轮
public void print15( int loop ) throws InterruptedException {
lock.lock();
try{
while( flag != 3 ){
c3.await();
}
for( int i = 0 ; i < 15 ; i++ ){
System.out.println( Thread.currentThread().getName() + "::" + i + ": 轮数:" + loop );
}
//修改标志位
flag = 1 ;
// 通知AA线程
c1.signal();
}finally{
lock.unlock();
}
}
}
public class LThreadDemo2 {
public static void main( String[] args ) {
ShareResource shareResource = new ShareResource();
new Thread( () -> {
for( int i = 1 ; i <= 10 ; i++ ){
try{
shareResource.print5(i);
}catch( InterruptedException e ){
e.printStackTrace();
}
}
} , "AA" ).start();
new Thread( () -> {
for( int i = 1 ; i <= 10 ; i++ ){
try{
shareResource.print10(i);
}catch( InterruptedException e ){
e.printStackTrace();
}
}
} , "BB" ).start();
new Thread( () -> {
for( int i = 1 ; i <= 10 ; i++ ){
try{
shareResource.print15(i);
}catch( InterruptedException e ){
e.printStackTrace();
}
}
} , "CC" ).start();
}
}