简单实现阻塞队列

队列:

package org.com.test.blockQueue;

import java.util.LinkedList;

public class BlockQueue {

    int max = 5;

    LinkedList<String> linkedList = new LinkedList<>();

    public synchronized void get() {
        //linkedList有元素就取出
        while (linkedList.size() != 0) {
            System.out.println("消费"+linkedList.poll());
        }
        //linkedList没元素就让出CPU
        try {
            System.out.println("blocking!!!");
            wait(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void put(String str) {
        //linkedList没满就加入队列
        while (linkedList.size() <= max) {
            System.out.println("生产:"+str);
            linkedList.offer(str);
            break;
        }
        //linkedList满了让出cpu
        try {
            wait(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

测试:

package org.com.test.blockQueue;

public class BlockTest {
    public static void main(String[] args) {
        BlockQueue blockQueue = new BlockQueue();
        //消费者
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 30; i++) {
                    blockQueue.get();
                }
            }
        }).start();
        //生产者1号
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 20; i++) {
                    blockQueue.put("生产者A:" + i+"号产品");
                }
            }
        }).start();
        //生产者2号
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 20; i++) {
                    blockQueue.put("生产者B:" + i+"号产品");
                }
            }
        }).start();
    }

}

 

结果:

 

posted @ 2018-07-13 17:40  上辈子怕是个傻子  阅读(156)  评论(0编辑  收藏  举报