-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerAndconsumer.java
More file actions
104 lines (84 loc) · 2.09 KB
/
Copy pathProducerAndconsumer.java
File metadata and controls
104 lines (84 loc) · 2.09 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
/**
* 线程之间的通信问题:生产者和消费者问题! 等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一变量 num=0
* A num+1
* B num-1
*/
public class ProducerAndconsumer {
public static void main(String[] args) {
Data data=new Data();
new Thread(()->{ for (int i=0;i<10;i++)
{
try{
data.increment();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{for (int i=0;i<10;i++)
{
try{
data.decrement();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{for (int i=0;i<10;i++)
{
try{
data.increment();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{for (int i=0;i<10;i++)
{
try{
data.decrement();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
},"D").start();
}
}
//等待,业务,通知
class Data{ //数字 资源类
int number =0;
// +1
public synchronized void increment() throws InterruptedException
{
while(number!=0)
{
//等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程 我+1 完毕了
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException
{
while(number==0)
{
//等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程 我-1完毕了
this.notifyAll();
}
}