public class CubbyHole {
private int seq; //数据
private boolean available=false; //条件变量
public synchronized int get() //消费数据
{
while(available==false) //无资源
{
try{
wait(); //挂起
}
catch(InterruptedException e){
}
}
available=false;
notify(); //唤醒
return seq;
}
public synchronized void put(int value) //生产数据
{
while(available==true) //已有资源
{
try{
wait(); //挂起
}
catch(InterruptedException e){
}
}
seq=value;
available=true;
notify(); //唤醒
}
}
public class Producer extends Thread{
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c,int number)
{
cubbyhole=c;
this.number=number;
}
public void run()
{
for(int i=0;i<10;i++) //共生产10个
{
cubbyhole.put(i);
System.out.println("Producer #"+this.number+" put: "+i);
try{
sleep((int)(Math.random()*100));
}
catch(InterruptedException e){}
}
}
}
public class Consumer extends Thread{
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c,int number)
{
cubbyhole=c;
this.number=number;
}
public void run()
{
int value=0;
for(int i=0;i<10;i++) //不间断地连续消费10个
{
value=cubbyhole.get();
System.out.println("Consumer #"+this.number+" got: "+value);
}
}
}
public class ProducerConsumeTest {
public static void main(String[] args) {
CubbyHole c=new CubbyHole(); //共享数据对象
Producer p1=new Producer(c,1);
Consumer c1=new Consumer(c,1);
p1.start();
c1.start();
}
}
运行结果:
学习心得:
生产者线程和消费者线程严格地轮流执行,获得了线程间的协调执行,达到了共享资源的互斥性操作;
synchronized同步:保证了一个线程在一个完整操作的所有步骤的执行过程中,都独占相关资源而不被打断。