forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonkeyDemo.java
More file actions
80 lines (70 loc) · 1.99 KB
/
MonkeyDemo.java
File metadata and controls
80 lines (70 loc) · 1.99 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
package ALiBaBa;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author MaoTian
* @Classname MonkeyDemo
* @Description TODO
* @Date 下午11:15 2019/8/18
* @Version 1.0
* @Created by mao<[email protected]>
*/
class Resource{
private int num=1119;
private ReentrantLock lock=new ReentrantLock();
private Condition condition1=lock.newCondition();
public void consumer(int k){
lock.lock();
try{
if(num-k<0){
condition1.await();
}
num=num-k;
if(k==2){
System.out.println("monkey A:"+k+",left:"+num);
}else{
System.out.println("monkey B:"+k+",left:"+num);
}
// condition1.notifyAll();
}catch(Exception e){
}finally{
lock.unlock();
}
}
}
public class MonkeyDemo {
public static void main(String[] args)throws Exception {
Resource resource=new Resource();
new Thread(()->{
while (true) {
resource.consumer(2);
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"monkey A").start();
new Thread(()->{
while(true) {
resource.consumer(3);
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"monkey B").start();
new Thread(()->{
while(true) {
resource.consumer(3);
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"monkey C").start();
}
}