import java.util.ArrayList;
import
java.util.List;
/**
* 消费者/生产者模式 问题:
* 1.一个共同容量确定的仓库,
* 2.生产者只管生产物品放到仓库,若仓库库满则等待,若库未满,继续生产放入,
* 3.消费者只管从仓库区物品,若库空则等待,若库未空,则取
* 4.消费者和生产者,相互不关联
*
* 代码: 1.创建物品类 2.容量一定的仓库类(存取) 3.消费者类(继承Thread) 4.生产者类(继承Thread)
*
*/
// 物品类
class
Goods {
public
int
id
;
public
Goods(){};
public
Goods(
int
id
) {
this
.
id
=
id
;
}
public
String toString() {
return
"goods"
+
id
;
}
}
// 仓库(物品类)
class
Store {
//用于存放goods的集合
private
Goods[]
lst
=
new
Goods[5];
int
index
=0;
//仓库容量的确定
//放
public
synchronized
void
put(Goods
goods
) {
System.
out
.println(
"put"
+
goods
.
id
);
while
(
index
==
lst
.
length
){
try
{
this
.wait();
}
catch
(InterruptedException
e
) {
//
TODO
Auto-generated catch block
e
.printStackTrace();
}
}
this
.notify();
lst
[
index
]=
goods
;
index
++;
}
//取
public
synchronized
Goods take(){
while
(
index
==0){
try
{
this
.wait();
}
catch
(InterruptedException
e
) {
//
TODO
Auto-generated catch block
e
.printStackTrace();
}
}
index
--;
this
.notify();
return
lst
[
index
];
}
}
//生产者
class
Producer
extends
Thread{
private
Store
store
;
public
void
setStore(Store
store
){
this
.
store
=
store
;
}
@Override
public
void
run() {
//生产物品
for
(
int
i
=0;
i
<30;
i
++){
Goods
g
=
new
Goods(
i
);
store
.put(
g
);
}
}
}
//消费者
class
Consumer
extends
Thread {
private
Store
store
;
public
void
setStore(Store
store
){
this
.
store
=
store
;
}
@Override
public
void
run() {
for
(
int
i
=0;
i
<30;
i
++){
System.
out
.println(
"take"
+
store
.take().
id
);
}
}
}
//测试
class
ProduceConsume {
public
static
void
main(String[]
args
) {
Store
store
=
new
Store();
Producer
producer
=
new
Producer();
Consumer
consumer
=
new
Consumer();
producer
.setStore(
store
);
consumer
.setStore(
store
);
producer
.start();
consumer
.start();
}
}