使用阻塞隊列存取數據
阿新 • • 發佈:2018-08-24
oid 運行 imp 存取 取數據 個數 pre catch ring 存數據queue.put(1);
取數據queue.take();
取數據queue.take();
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class BlockingQueueTest { public static void main(String[] args) { //自定義隊列能存放3個數據 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(); } }
使用阻塞隊列存取數據