Java生产者消费者

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
126
import java.util.Vector;
//工厂
class Factory
{
private Vector<String> goods;
private int goodFlag = 5;//货物上限
public Factory(){
goods = new Vector<String> ();
}
public synchronized void production()
{
if (goods.size() < goodFlag) {
goods.addElement("货物"+(goods.size()+1));
System.out.printf("%s生产货物:货物%d,现有货物数量:%d\n", Thread.currentThread().getName(),
(goods.size() + 1),goods.size());
notifyAll();
}
else {
System.out.println("货物已满可以取货");
try
{
// 货物满等待消费
wait();
}
catch (InterruptedException e)
{
System.out.println("生产事故...");
}
}
}
public synchronized void getProduction()
{
if (goods.size() < 1)
{
try
{
System.out.println("货物取完...");
// 等待生产
wait();
}
catch (InterruptedException e)
{
System.out.println("账户余额不足...");
}
}
else
{
System.out.printf("%s取走货物:%s,还有货物数量:%d\n", Thread.currentThread().getName(),
goods.elementAt(goods.size() - 1),
goods.size());
goods.remove(goods.size() - 1);
// 唤醒生产线程
notifyAll();
}
}
}
//生产者
class ProductThread extends Thread
{
private Factory factory = null;
public ProductThread(String name,Factory factory)
{
super(name);
this.factory=factory;
}
public void run()
{
while (true)
{
factory.production();
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
System.out.println("生产事故...");
}
}
}
}
//消费者
class ConsumThread extends Thread
{
private Factory factory = null;
public ConsumThread(String name, Factory factory)
{
super(name);
this.factory = factory;
}
@Override
public void run()
{
while (true)
{
factory.getProduction();
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
System.out.println("账户余额不足...");
}
}
}
}
class ProducConsumDome
{
public static void main(String[] args) {
Factory factory = new Factory();
ProductThread productThread = new ProductThread("生产工厂", factory);
ConsumThread consumThread = new ConsumThread("消费者", factory);
productThread.start();
consumThread.start();
}
}
文章目录
|