根据ReentrantLock和Condition创建阻塞队列

package com.test.day;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 写一个自定义阻塞队列,根据ReentrantLock和Condition
 */
public class MyBlockingQueue<E> {

	private ReentrantLock lock =new ReentrantLock();
	private Condition condition = lock.newCondition();

	private List<E> list = new ArrayList<>();
	int count;
	private final int MAX_SIZE;
	public MyBlockingQueue(int max){
		this.MAX_SIZE = max;
	}


	public void put(E obj){
		lock.lock();
		try{
			if(list.size() == MAX_SIZE){
				System.out.println("put 线程阻塞了");
				condition.await();
			}
			count++;
			list.add(obj);
			System.out.println("向队列添加元素"+obj);
			condition.signal();

		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public E take(){
		E obj = null;
		lock.lock();
		try{
			if(list.isEmpty()){
				System.out.println("take 阻塞了");
				condition.await();
			}
			obj = list.get(0);
			System.out.println("take---"+obj);
			list.remove(obj);
			condition.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return obj;
	}

	public static void main(String[] args) {
		MyBlockingQueue<Integer> demo = new MyBlockingQueue<>(5);
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<10;i++){
					demo.put(i);
				}
			}
		});


		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true) {
					demo.take();
				}
			}
		});

		t2.start();
		t1.start();
	}
}

你可能感兴趣的:(java,并发,多线程,java)