生产者/消费者模式(二)

生产者/消费者模式

第二种方法,信号灯法

代码

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
/**
* 消费者模式:信号灯法。
*
*/
public class Consumer_Model2 {
public static void main(String[] args) {
Shoping s=new Shoping();
Warehouse1 wa =new Warehouse1(s);
people pe= new people(s);
wa.start();
pe.start();
}
}
//生产商
class Warehouse1 extends Thread{
private Shoping shop;
public Warehouse1(Shoping shop) {
this.shop = shop;
}

@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println("---------------------");
System.out.println("生产第"+(i+1)+"个产品");
shop.put(new Wood(i));
}
}
}
//消费者
class people extends Thread{
private Shoping shop;
public people(Shoping shop) {
this.shop = shop;
}
@Override
public void run() {
for(int i=0;i<10;i++)
{
System.out.println("消费第"+(shop.take().getId()+1)+"个产品");
System.out.println("---------------------");
}
}
}
//中间商
class Shoping{
private Wood []i=new Wood[10];
private int count=0;
private boolean flag=true;
//放入数据
public synchronized void put(Wood wood) {
if(!flag)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i[count]=wood;
count++;
flag=false;
this.notifyAll();
}
//取出数据
public synchronized Wood take() {
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Wood b=i[count];
flag=true;
this.notifyAll();
return b;
}
}
//商品
class Wood{
private int id;
public Wood(int id) {
this.id = id;
}
public int getId() {
return id;
}
}

总结

线程并发协作(也叫线程通信),通常用于生产者/消费者模式,情景如下:

1. 生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。

2. 对于生产者,没有生产产品之前,消费者要进入等待状态。而生产了产品之后,又需要马上通知消费者消费。

3. 对于消费者,在消费之后,要通知生产者已经消费结束,需要继续生产新产品以供消费。

4. 在生产者消费者问题中,仅有synchronized是不够的。

synchronized可阻止并发更新同一个共享资源,实现了同步;

synchronized不能用来实现不同线程之间的消息传递(通信)。

5. 以上方法均是java.lang.Object类的方法;

都只能在同步方法或者同步代码块中使用,否则会抛出异常。

原创技术分享,您的支持将鼓励我继续创作
0%