import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; /** *ArrayBlockingQueue: 是一个基于数组结构的有界阻塞队列,此队列按照FIFO(先进先出)原则对元素进行排序; *LinkedBlockingDeque:一个基于链表结构的有界阻塞队列(默认为Integer。MAX_VALUE 21忆),此队列按照FIFO(先进先出)原则对元素进行排序,吞吐量高于ArrayBlockingQueue *SynchronousQueue同步队列,单个元素:一个不存储元素的阻塞队列,每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量高于LinkedBlockingDeque * 1 队列 按照FIFO(先进先出)原则对元素进行排序; * 2 阻塞队列(食品柜台):当阻塞队列是空时,从队列中获取元素的操作将会被阻塞;当阻塞队列是满时,往队列中添加元素的操作被阻塞 *好处:不需要考虑什么时候唤醒线程,什么时候阻塞线程。降低代码复杂度。似自动档车和手动挡车 * * */ public class BlockingQueneDemo { public static void main(String[] args) { // List<String> list = new ArrayList<>(); // BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3); // BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>(3); final BlockingQueue<String> blockingQueue = new SynchronousQueue<>(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { blockingQueue.put("1"); blockingQueue.put("2"); blockingQueue.put("3"); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.setName("a"); thread.start(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); System.out.println(blockingQueue.take()); Thread.sleep(5000); System.out.println( blockingQueue.take()); Thread.sleep(5000); System.out.println( blockingQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread1.setName("b"); thread1.start(); } }
ArrayBlockingQueue的方法: