您的位置:首页 > 编程语言 > Java开发

java 生产者与消费者问题实现

2014-06-15 14:07 393 查看
调用wait的时候让出了对象锁

import java.util.*;
public class ProducerConsumer{
public static void main(String []args){
SynStack ss= new SynStack();
Producer p = new Producer(ss,"Producer");
Consumer c = new Consumer(ss,"Consumer");
Thread pt = new Thread(p);
Thread ct = new Thread(c);
pt.start();
ct.start();
}
}

/*
*要生产的对象
*/
class Product{
int id ; //标示是哪个产品
public Product(int id){
this.id = id ;
}

public String toString(){
return "product:"+id;
}
}

///共享的缓冲区
class SynStack{
Product products[] = new Product[4]; //设置改缓冲区的大小为4个Product
int top = 0; //记录此时缓冲区(栈)中的位置
public synchronized void push(Product p){
while(top == products.length){
try{
this.wait(); //如果缓冲区处于满状态则让生产操作处于wait,此时对象锁也被释放
}catch(InterruptedException e){
e.printStackTrace();
}
}

products[top] = p ; //将生产的产品加入缓冲区
top ++;
this.notifyAll(); //如果不是满状态则唤醒当前所有处于////等待状态的线程,因此消费者线程也被唤醒进行消费,如果不是多生产者与多消费者只//需要this.notify()即可
}

public synchronized Product pop(){
//System.out.println(top);
while(top == 0){
//System.out.println(top+"*");
try{
this.wait(); //如果缓冲区处于空状态则让消费操作////处于wait,此时对象锁也被释放
}catch(InterruptedException e){
e.printStackTrace();
}
}

top --;
this.notifyAll();
return products[top]; //返回当前栈顶对象

}

}
//生产者.是一个多线程类
class Producer implements Runnable{
String producerName;
SynStack ss = null;

/*public Producer(String name){
this.producerName = name ;
}*/

Producer(SynStack ss,String name) {
this.ss = ss;
this.producerName = name;
}

public void run(){
for(int i = 0 ;i<10;i++){
Product p = new Product(i);
ss.push(p);
System.out.println("生产者:"+producerName+"生产了:"+p.toString());
try{
Thread.sleep((int)(Math.random() * 500));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}

}

class Consumer implements Runnable{
String consumerName;
SynStack ss = null;
/*Consumer(String name ){
this.consumerName = name;
}*/
Consumer(SynStack ss,String name) {
this.ss = ss;
this.consumerName = name;
}
public void run(){
for(int i = 0;i<10;i++){
Product p = ss.pop();
System.out.println("消费者:"+consumerName+"消费了:"+p.toString());
try{
Thread.sleep(0);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息