/** * * @描述: 隊列(阻塞/非阻塞)、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(); } }