并发编程-基础篇(二)

北慕城南 提交于 2020-03-11 18:35:59

问题:利用队列+线程手写生产者和消费者?

public class Thread1 {
   static volatile LinkedBlockingQueue<Integer> queue=new LinkedBlockingQueue<>(5);

    @SneakyThrows
    public static void main(String[] args) {

       new Thread(new Productor()).start();
       new Thread(new Consumer()).start();
    }

    // 生产者
    static  class  Productor implements Runnable{
        @Override
        public void run() {
            productor(queue);
        }

        @SneakyThrows
        public static void  productor(LinkedBlockingQueue<Integer> queue){
            // 有10个待生产的数据
            for (int i = 0; i < 10; i++) {
                synchronized (queue){
                    // 条件有限 一次只能生产5个
                    if(queue.size()==5){
                        // 满了5个 之后 剩余的待生产个数都在等在着被生产
                        // 在挂起的时候一定要获取到对象锁,没有获取到对象锁会报异常
                        queue.wait();
                    }
                    // 空闲则生产元素
                    queue.add(i);
                    System.out.println("我在生产元素,哈哈哈");
                    queue.notifyAll();
                }

            }

        }
    }

     // 消费者
    static class  Consumer implements  Runnable{
        @Override
        public void run() {
            consumer(queue);
        }

        @SneakyThrows
        public static void consumer(LinkedBlockingQueue<Integer> queue){
             // 有10个待消费
            for (int i = 0; i < 10; i++) {
               
                synchronized (queue){
                    if(queue.size()==0){
                        queue.wait();
                    }
                    queue.take();
                    System.out.println("我在消费元素,哈哈哈");
                    queue.notifyAll();
                }
            }

        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!