/** * * @描述: 队列(阻塞/非阻塞)、LinkedQueue不固定大小 * 先进先出,如队列大小为8,如放进了8个数据,就不能继续放了,会进入阻塞,若是是非阻塞队列则会报错 * * Throwsexception Special value()返回值判断 Blocks(阻塞) Times out Insert add(e) offer(e) put(e) offer(e, time, unit) Remove remove() poll() take() poll(time, unit) Examine element() peek() not applicable not applicable Java中的原子性,是指:原子操做是不能被线程调度机制中断的;操做一旦开始,它必定会在可能发生的“上下文切换”(即切换到其余线程执行) 以前执行完毕。 可是千万不要认为“原子操做不须要同步控制(这是错误的)” * @做者: Wnj . * @建立时间: 2017年5月16日 . * @版本: 1.0 . */ public class BlockingQueueTest { public static void main(String[] args) { final BlockingQueue queue = new ArrayBlockingQueue(3); for (int i = 0; i < 2; i++) { new Thread() { public void run() { while (true) { try { Thread.sleep((long)(Math.random() * 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() { public void run() { while (true) { try { //将此处的睡眠时间分别改成100和1000,观察运行结果 Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "准备取数据!"); queue.take(); System.out.println(Thread.currentThread().getName() + "已经取走数据," + "队列目前有" + queue.size() + "个数据"); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } }