Java 并发编程 消息队列、阻塞队列

消息队列

package Thread;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class Mycontainer<T> {
    private LinkedList<T> list = new LinkedList<>();
    final int MAX = 10;
    private int count = 0;
    Lock lock = new ReentrantLock();
    Condition procuder = lock.newCondition();
    Condition consumer = lock.newCondition();

    public void put(T t) {
        lock.lock();
        while (list.size() == MAX) {
            try {
                procuder .await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(t);
        count++;
        consumer .signalAll();
        lock.unlock();
    }


    public T get() {
        lock.lock();
        while (list.size() == 0) {
            try {
                consumer .await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        T t = list.removeFirst();
        count--;
        procuder .signalAll();
        lock.unlock();
        return t;
    }

    public synchronized int getCount() {
        return count;
    }

// 测试生产者消费者 
    public static void main(String[] args) {
        Mycontainer<String> mycontainer = new Mycontainer<String>();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(mycontainer.get());
                }
            }, "C" + i).start();

        }

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    mycontainer.put(Thread.currentThread().getName() + " " + j);
                }
            }, "P" + i).start();

        }
    }
}

阻塞队列

package Thread;

import java.util.LinkedList;
import java.util.List;

public class BlokedQueue {

    private List queue = new LinkedList();
    private int limit = 10;

    public BlokedQueue(int limit) {
        this.limit = limit;
    }

    public synchronized void enQueue(int item) throws InterruptedException {
        while (queue.size() == limit) {
            wait();
        }
        if (queue.size() == 0) {
            notifyAll();
        }
        this.queue.add(item);
    }

    public synchronized int deQueue() throws InterruptedException {
        while (queue.size() == 0) {
            wait();
        }
        if (queue.size() == limit) {
            notifyAll();
        }

        return (int) queue.remove(0);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值