您的位置:首页 > 其它

多线程--生产者和消费者

2015-07-04 15:19 330 查看
生产者-消费者问题:

生产者向产品区里放产品,当产品区里满了,需要等待;消费者从产品区里取产品消耗,当产品区里空了,需要等待。

public class ProducerAndConsumer
{
//创建缓冲区
private static Buffer buffer = new Buffer();

public static void main(String[] args)
{
System.out.println("Hello World!");
Thread producer = new Thread(new Producer());
Thread consumer = new Thread(new Consumer());
consumer.start();
producer.start();

}

//消费者
static class Consumer implements Runnable
{
public void run(){
try{
while(true){
buffer.poll();
Thread.sleep((int)(Math.random()*1000));
}
}catch(InterruptedException ex){}
}
}
//生产者
static class Producer implements Runnable
{
public void run(){
try{
while(true){
buffer.push(new Random().nextInt(20));
Thread.sleep((int)(Math.random()*1000));
}
}catch(InterruptedException ex){}
}
}
}

//缓冲池
class Buffer
{
//创建锁
private static Lock lock = new ReentrantLock();
//条件1---缓冲池空
private static Condition empty = lock.newCondition();
//条件2---缓冲池满
private static Condition full = lock.newCondition();
//缓冲池大小
private static final int  size =  10;
//缓冲池
private Queue<Integer> queue = new LinkedList<Integer>();

//取数
public void poll(){
lock.lock();
try{
while(queue.size() == 0){
System.out.println("\t\t\t\tWait for producer:");
empty.await();
}
int num = queue.poll();
System.out.println("\t\t\t\t["+queue.size()+"]poll:" + num);
full.signal();
}catch(InterruptedException ex){

}finally{
lock.unlock();
}

}
//存数
public void push(int num){
lock.lock();
try{
while(queue.size() == 10){
System.out.println("Wait for consumer:");
full.await();
}
queue.offer(num);
System.out.println("["+queue.size()+"]push:" + num);
empty.signal();
}catch(InterruptedException ex){

}finally{
lock.unlock();
}
}
}


多个生产者-多个消费者问题

由于产品区是互斥访问的,一次只有一个线程能够进入产品区,所以和上面的几乎一样,只是多加一个进程(不知道理解的是否对)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: