并发编程-LinkedBlockingQueue实现生产者和消费者
package cn.bikan8;


import java.util.concurrent.LinkedBlockingQueue;



/**
 * @Author 小浩
 * @Date 2020/5/28 16:21
 * @Version 1.0
 **/
public class Buffer {
    private LinkedBlockingQueue<Object> linkedBlockingQueue = new LinkedBlockingQueue<>();


    /**
     * 消费者消费
     */
    public void take() {

        try {
            Object o = linkedBlockingQueue.take();
            System.out.println(Thread.currentThread().getName() + "消费了" + o.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    /**
     * 生产者生产
     */
    public void put() {
        try {
            Object o = new Object();

            linkedBlockingQueue.put(o);
            System.out.println(Thread.currentThread().getName() + "生产了" + o.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}
package cn.bikan8;

/**
 * @Author 小浩
 * @Date 2020/5/28 16:45
 * @Version 1.0
 **/
public class Producer implements  Runnable {
    private Buffer buffer;

    public Producer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        while (true){

            buffer.put();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
package cn.bikan8;

/**
 * @Author 小浩
 * @Date 2020/5/28 16:47
 * @Version 1.0
 **/
public class Consumer implements  Runnable {
    Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        while (true){

            buffer.take();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
package cn.bikan8;

/**
 * @Author 小浩
 * @Date 2020/5/28 16:48
 * @Version 1.0
 **/
public class Test {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();

        Thread consumer1 = new Thread(new Consumer(buffer));
        Thread consumer2 = new Thread(new Consumer(buffer));
        Thread consumer3 = new Thread(new Consumer(buffer));
        Thread producer1 = new Thread(new Producer(buffer));
        Thread producer2 = new Thread(new Producer(buffer));
        consumer1.start();
        consumer2.start();
        consumer3.start();
        producer1.start();
        producer2.start();

    }
}

 

© 版权声明
THE END
喜欢就支持以下吧
点赞0
分享
评论 抢沙发