ArrayBlockingQueue是由数组支持的有界阻塞队列,次队列按照FIFO(先进先出)原则,当队列已经填满,在去增加则会导致阻塞,这种阻塞类似线程阻塞。
ArrayBlockingQueue提供的增加和取出方法总结
使用ArrayBlockingQueue的一个子类BlockingQueue实现一个可阻塞队列,一个线程put另一个线程take,当队列为空时take等待,当线程满时put等待
此实现方式没有线程互斥
import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * 可阻塞的队列 * BlockingQueue * 此方式不能实现线程互斥 * @author * */ public class BlockingQueueCommunicationTest { public static void main(String[] args) { final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(new Random().nextInt(1000)); System.out.println("线程" + Thread.currentThread().getName() + "准备增加"); queue.put(1); System.out.println("线程" + Thread.currentThread().getName() + "已增加,队列有" + queue.size() + "个"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(new Random().nextInt(1000)); System.out.println("线程" + Thread.currentThread().getName() + "准备取走"); queue.take(); System.out.println("线程" + Thread.currentThread().getName() + "已取走,队列剩余" + queue.size() + "个"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } } |