java之BlockingQueue实现生产者消费者

直接上代码
注意在使用blockingqueue实现生产者消费者模型时候,BlockingQueue泛型使用若atomic等对象时候会发现消费者出现异常,这是因为传值和传引用的区别,而Integer因为java的自动装箱不会出现此类问题,具体可自行尝试java

生产者ide

public class Pull implements Runnable {

    BlockingQueue<Integer> pool;

    Integer product = 0;

    public Pull(BlockingQueue<Integer> pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        while (true) {
            try {
                pool.put(product);
                System.out.println("add:" + product);
                product++;
            } catch (InterruptedException e) {
                System.out.println("add failed");
                e.printStackTrace();
            }

            if (product == 20){
                break;
            }

        }
    }
}

消费者this

public class Push implements Runnable{

    BlockingQueue<Integer> pool;

    public Push(BlockingQueue<Integer> pool) {
        this.pool = pool;
    }

    @Override
    public void run() {

        while(true) {
            try {
                Integer tmp = pool.take();
                System.out.println("take:" + tmp);
            } catch (InterruptedException e) {
                System.out.println("获取失败");
                e.printStackTrace();
            }
        }
    }
}

主线程atom

public class MyExecutor {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new LinkedBlockingDeque<>(10);
        Thread thread = new Thread(new Push(queue));
        Thread thread1 = new Thread(new Pull(queue));
        thread1.start();
        thread.start();
    }
}
相关文章
相关标签/搜索