模拟一个生产者-消费者关系的程序。
其中包含5个类
1.主控类ProducerConsmer
2.共享数据类MyData
3.共享数据控制类ShareData
4.生产者线程类Producer
5.消费者线程类Consmer
class ProducerConsmer{ // 1---------------主控类
public static void main(String[] agrs){
ShareData sd=new ShareData();
Producer pro=new Producer(sd);
Consmer con=new Consmer(sd);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
t1.start();
t2.start();
}
}
class MyData{ // 2---------------共享数据类
public int id;
}
class ShareData{ // 3-------------共享数据控制类
private MyData data; //共享数据
private boolean notice=true; //通知变量 true--标记消费,false--标记生产
public synchronized void set(MyData data){ //生产工作
while(!notice){ //未消费,则等待
try{
this.wait();
}catch(InterruptedException e){
}
}
this.data=data;
notice=false; //标记生产者已经生产
this.notify(); //通知消费者消费
}
public synchronized MyData get(){ //消费工作
while(notice){ //未生产,则等待
try{
this.wait();
}catch(InterruptedException e){
}
}
notice=true; //标记消费者已经消费
this.notify(); //通知生产者生产
return this.data;
}
}
class Producer implements Runnable{ // 4--------------生产者线程类
private ShareData sd;
Producer(ShareData sd){
this.sd=sd;
}
public void run(){
for(int i=0;i<=10;i++){
MyData mydata=new MyData();
mydata.id=i;
sd.set(mydata);
System.out.println("生产者生产一条数据: "+mydata.id);
try{
Thread.sleep((int)Math.random()*100);
}catch(InterruptedException e){
}
}
}
}
class Consmer implements Runnable{ // 5--------------消费者线程类
private ShareData sd;
Consmer(ShareData sd){
this.sd=sd;
}
public void run(){
for(int i=0;i<=10;i++){
MyData mydata=sd.get();
System.out.println("消费者消费一条数据: "+mydata.id);
}
try{
Thread.sleep((int)Math.random()*100);
}catch(InterruptedException e){
}
}
}
运行结果:
消费者消费一条数据: 0
生产者生产一条数据: 0
生产者生产一条数据: 1
消费者消费一条数据: 1
生产者生产一条数据: 2
消费者消费一条数据: 2
……
……
消费者消费一条数据: 9
生产者生产一条数据: 9
消费者消费一条数据: 10
生产者生产一条数据: 10