forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadDemo.java
More file actions
91 lines (80 loc) · 1.9 KB
/
ThreadDemo.java
File metadata and controls
91 lines (80 loc) · 1.9 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
package ALiBaBa;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author MaoTian
* @Classname ThreadDemo
* @Description TODO
* @Date 下午4:41 2019/8/19
* @Version 1.0
* @Created by mao<[email protected]>
*/
class ResourceDemo{
private volatile int num=0;
ReentrantLock lock=new ReentrantLock();
Condition c1=lock.newCondition();
Condition c2=lock.newCondition();
Condition c3=lock.newCondition();
public void printA(){
lock.lock();
try{
while(num!=0){
c1.await();
}
System.out.print("A");
}catch(Exception e){
}finally{
num=1;
c2.signal();
lock.unlock();
}
}
public void printB(){
lock.lock();
try{
while(num!=1){
c2.await();
}
System.out.print("B");
}catch(Exception e){
}finally{
num=2;
c3.signal();
lock.unlock();
}
}
public void printC(){
lock.lock();
try{
while(num!=2){
c3.await();
}
System.out.print("C");
}catch(Exception e){
}finally{
num=0;
c1.signal();
lock.unlock();
}
}
}
public class ThreadDemo{
public static void main(String[] args){
ResourceDemo resourceDemo=new ResourceDemo();
new Thread(()->{
for(int i=0;i<10;i++){
resourceDemo.printA();
}
},"Thread A").start();
new Thread(()->{
for(int i=0;i<10;i++){
resourceDemo.printB();
}
},"Thread B").start();
new Thread(()->{
for(int i=0;i<10;i++){
resourceDemo.printC();
}
},"Thread C").start();
}
}