一道关于生产者与消费的线程同步
本程序如何修改才能达到下面的效果:
生产的新数据是:1
读到的数据是:1
生产的新数据是:2
读到的数据是:2
生产的新数据是:3
读到的数据是:3
生产的新数据是:4
读到的数据是:4
源文件:
package 多线程;
//生产者与消费者的同步问题 。生产者放入一个整数到共享区中,仅当消费者取走后才能继续放入
class HoldInt{
private int sharedInt; //共享区只能存入一个数
private boolean writeAble = true;//表示生产者能生产新数据
public synchronized void set(int val){ //对临界区的写操作
while(!writeAble){ //进入等待
try{
wait();
}catch(InterruptedException e){}
}
sharedInt = val;
writeAble = false; //表示生产者不能放入数据
notify();//唤醒消费者
}
public synchronized int get(){ //对临界区的读操作
while(writeAble){
try{
wait();
}catch(InterruptedException e){}
}
writeAble = true;
notify();//唤醒生产者
return sharedInt;
}
}
//生产者线程
class ProduceInt extends Thread{
private HoldInt hi;
public ProduceInt(HoldInt hiForm){
hi = hiForm;
}
public void run(){
for(int i=1;i<=4;i++){
hi.set(i);
System.out.println("生产的新数据是:"+i);
}
}
}
//消费者线程
class ConsumeInt extends Thread{
private HoldInt hi;
public ConsumeInt(HoldInt hiForm){
hi = hiForm;
}
public void run(){
for(int i=1;i<=4;i++){
int val = hi.get();
System.out.println("读到的数据是:"+val);
}
}
}
public class Productor_Consumer {
public static void main(String[] args){
HoldInt h = new HoldInt();//h为监控器
ProduceInt p = new ProduceInt(h);
ConsumeInt c = new ConsumeInt(h);
p.start();
c.start();
}
}