多线程实现生产者消费者

一、采用synchronized锁以及wait notify方法实现
1.wait()的作用是让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)
2.notify()和notifyAll()的作用,则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。
3.wait(long timeout)让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)。

//主类
public class WaitAndNotify {
    public static void main(String[] args) {
        Person person = new Person();
        new Thread(new Consumer("消费者一", person)).start();
        new Thread(new Consumer("消费者二", person)).start();
        new Thread(new Consumer("消费者三", person)).start();

        new Thread(new Producer("生产者一", person)).start();
        new Thread(new Producer("生产者二", person)).start();
        new Thread(new Producer("生产者 三", person)).start();
    }
}

//生产者
public class Producer implements Runnable {
    private Person person;
    private String producerName;
    public Producer(String producerName, Person person) {
        this.producerName = producerName;
        this.person = person;
    }
    public void run() {
        while(true) {
            try {
                person.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//消费者
public class Consumer implements Runnable {
    private Person person;
    private String consumerName;
    public Consumer(String consumerName, Person person) {
        this.consumerName = consumerName;
        this.person = person;
    }
    public void run()
    {
        while(true) {
            try
            {
                person.consume();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }   
    }
}

//Person 类
public class Person {
    private int foodNum = 0;
    private Object synObject = new Object();
    private final int MAX_NUM = 10;
    public void produce() throws InterruptedException 
    {
        synchronized (synObject) {
            while(foodNum == MAX_NUM)
            {
                System.out.println("ThreadId: " + Thread.currentThread().getId() + "  box is full, size = " + foodNum);
                synObject.wait();
            }
            foodNum++;
            System.out.println("produce success foodNum = " + foodNum);
            synObject.notifyAll();
        }
    }
    public void consume() throws InterruptedException 
    {
        synchronized (synObject) {
            while(foodNum == 0) {
                System.out.println("ThreadId: " + Thread.currentThread().getId() + "   box is empty, size = " + foodNum);
                synObject.wait();
            }
            foodNum--;
            System.out.println("consume success foodNum = " + foodNum);
            synObject.notifyAll();
        }
    }
}

二、采用Lock锁以及await和signal方法是实现

//主类
public class AwaitAndSignal{
    public static void main(String[] args) {
        Person person = new Person();
        new Thread(new Consumer("消费者一", person)).start();
        new Thread(new Consumer("消费者二", person)).start();
        new Thread(new Consumer("消费者三", person)).start();

        new Thread(new Producer("生产者一", person)).start();
        new Thread(new Producer("生产者二", person)).start();
        new Thread(new Producer("生产者 三", person)).start();
    }
}
//生产者
public class Producer implements Runnable {
    private Person person;
    private String producerName;
    public Producer(String producerName, Person person) {
        this.producerName = producerName;
        this.person = person;
    }
    public void run() {
        while(true) {
            try {
                person.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//消费者
public class Consumer implements Runnable {
    private Person person;
    private String consumerName;
    public Consumer(String consumerName, Person person) {
        this.consumerName = consumerName;
        this.person = person;
    }
    public void run()
    {
        while(true)
        {
            try
            {
                person.consume();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

//Person 类
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Person {
    private int foodNum = 0;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private final int MAX_NUM = 10;
    public void produce() throws InterruptedException 
    {
        lock.lock();
        try 
        {
            while(foodNum == MAX_NUM)
            {
                System.out.println("ThreadId: " + Thread.currentThread().getId() + "  box is full, size = " + foodNum);
                condition.await();
            }
            foodNum++;
            System.out.println("produce success foodNum = " + foodNum);
            condition.signalAll();
        }catch(InterruptedException e) {
            e.printStackTrace();
        }finally
        {
            lock.unlock();
        }
    }
    public void consume() throws InterruptedException 
    {
        lock.lock();
        try
        {
            while(foodNum == 0) {
                System.out.println("ThreadId: " + Thread.currentThread().getId() + "   box is empty, size = " + foodNum);
                condition.await();
            }
            foodNum--;
            System.out.println("consume success foodNum = " + foodNum);
            condition.signalAll();
        }catch(InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

三。下面是用ConcurrentLinkedQueue实现的, 我觉得是有bug的,先放在这里。
非阻塞队列
基于链接节点的、无界的、线程安全。此队列按照 FIFO(先进先出)原则对元素进行排序。队列的头部 是队列中时间最长的元素。队列的尾部 是队列中时间最短的元素。新的元素插入到队列的尾部,队列检索操作从队列头部获得元素。当许多线程共享访问一个公共 collection 时,ConcurrentLinkedQueue 是一个恰当的选择。此队列不允许 null 元素。

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class NoBlockQueue {
    private static ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<Integer>();
    private static ReentrantLock lock = new ReentrantLock();
    //private static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        executorService.submit(new Producer("producer1"));
        executorService.submit(new Producer("producer2"));
        executorService.submit(new Producer("producer3"));
        executorService.submit(new Consumer("consumer1"));
        executorService.submit(new Consumer("consumer2"));
        executorService.submit(new Consumer("consumer3"));
    }
    static class Producer implements Runnable {
        private String name;
        int cnt = 0;
        public Producer(String name) {
            this.name = name;
        }
        public void run() {
            while(true) {
                System.out.println(name + " start producer " + cnt + "  " + Thread.currentThread().getId());
                concurrentLinkedQueue.add(cnt++);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
    static class Consumer implements Runnable {
        private String name;
        public Consumer(String name) {
            this.name = name;
        }
        public void run() {
            while(true) 
            {
                //我觉得这里是有bug, 可能一个线程判断不空,但是取的时候已经为空了,如果给concurrentLinkedQueue加锁有限制了并发!
                if(concurrentLinkedQueue.isEmpty()) {
                    System.out.println("concurrentLinkedQueue is empty!");
                } else {
                    System.out.println(name + " Consumer " + concurrentLinkedQueue.poll());
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

四。利用LinkedBlockingQueue实现生产者消费者问题。
按 FIFO(先进先出)排序元素。队列的头部 是在队列中时间最长的元素。队列的尾部 是在队列中时间最短的元素。新元素插入到队列的尾部,并且队列检索操作会获得位于队列头部的元素。链接队列的吞吐量通常要高于基于数组的队列,但是在大多数并发应用程序中,其可预知的性能要低。

注意:

1、必须要使用take()方法在获取的时候达成阻塞结果
2、使用poll()方法将产生非阻塞效果

public class BlockingQueue{
    //阻塞队列,FIFO
    private static LinkedBlockingQueue<Integer> concurrentLinkedQueue = new LinkedBlockingQueue<Integer>();

 public static void main(String[] args) {  
     ExecutorService executorService = Executors.newFixedThreadPool(6);  

     executorService.submit(new Producer("producer1"));  
     executorService.submit(new Producer("producer2"));  
     executorService.submit(new Producer("producer3"));  
     executorService.submit(new Consumer("consumer1"));  
     executorService.submit(new Consumer("consumer2"));  
     executorService.submit(new Consumer("consumer3"));  
 }  

 static class Producer implements Runnable {
     private String name;  
     int cnt = 0;
     public Producer(String name) {  
         this.name = name;  
     }

     public void run() {  
          while(true) {
             System.out.println(name+ "  生产: " + cnt);
             //concurrentLinkedQueue.add(i);  
             try {
                concurrentLinkedQueue.put(cnt++);
                Thread.sleep(3000); //模拟慢速的生产,产生阻塞的效果
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
         }
     }  
 }  

 static class Consumer implements Runnable {  
     private String name;  

     public Consumer(String name) {  
         this.name = name;  
     }  
     public void run() {  
         while(true) {
             try {          
                //必须要使用take()方法在获取的时候阻塞
                  System.out.println(name+"消费: " +  concurrentLinkedQueue.take()); 
                  Thread.sleep(2000);
                  //使用poll()方法 将产生非阻塞效果
                  //System.out.println(name+"消费: " +  concurrentLinkedQueue.poll());  
                  //还有一个超时的用法,队列空时,指定阻塞时间后返回,不会一直阻塞
                  //System.out.println(name+" Consumer " +  concurrentLinkedQueue.poll(300, TimeUnit.MILLISECONDS));                    
            } catch (Exception e) {
                e.printStackTrace();
            }  
         }
     }  
 }  
}

在并发编程中,一般推荐使用阻塞队列,这样实现可以尽量地避免程序出现意外的错误。阻塞队列使用最经典的场景就是socket客户端数据的读取和解析,读取数据的线程不断将数据放入队列,然后解析线程不断从队列取数据解析。还有其他类似的场景,只要符合生产者-消费者模型的都可以使用阻塞队列。

使用非阻塞队列,虽然能即时返回结果(消费结果),但必须自行编码解决返回为空的情况处理(以及消费重试等问题)。
另外他们都是线程安全的,不用考虑线程同步问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值