1.构建共同操作模型
class
Info{
private
String
title
;
private
String
content
;
private
Boolean
flag
=
true
;
//true 可以生产,不能取走
//
flase
不能生产,必须取走
public
synchronized
void
Set(String title,String content){
if
(
flag
==
false
) {
try
{
super
.wait();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
this
.
title
= title;
this
.
content
= content;
flag
=
false
;
super
.notify();
}
public
synchronized
void
get(){
if
(
flag
==
true
) {
try
{
super
.wait();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
System.
out
.println(
this
.
title
+
"----"
+
this
.
content
);
flag
=
true
;
super
.notify();
}
}
2.构建生产者,实现Runnable接口
class
Productor
implements
Runnable{
private
Info
info
=
null
;
public
Productor(Info info){
this
.
info
= info;
}
@Override
public
void
run() {
//
TODO
Auto-generated method stub
for
(
int
i=0;i<50;i++){
if
(i%2==0) {
this
.
info
.Set(
"小黑"
,
"坏蛋"
);
try
{
Thread.
sleep
(100);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
else
{
this
.
info
.Set(
"小红"
,
"好人"
);
try
{
Thread.
sleep
(100);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
3.构建消费者,
class
Consumer
implements
Runnable{
private
Info
info
;
public
Consumer(Info info){
this
.
info
= info;
}
@Override
public
void
run() {
//
TODO
Auto-generated method stub
for
(
int
i = 0; i <50; i++) {
try
{
Thread.
sleep
(100);
}
catch
(InterruptedException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
this
.
info
.get();
}
}
}
4.main方法测试
Info info = new Info();
Productor productor = new Productor(info);
Consumer consumer = new Consumer(info);
new Thread(productor).start();
new Thread(consumer).start();
5.总结:
1).构建info的信息,在get和set方法加锁可以保证数据不会乱,但是会重,连着取走两条重复的数据,要解决这个问题,做个标记,必须是生产完一条,取走一条.
2).调用一个Object的wait与notify/notifyAll的时候,必须保证调用代码对该Object是同步的,也就是说必须在作用等同于synchronized(obj){......}的内部才能够去调用obj的wait与notify/notifyAll三个方法。