並發的集合類
阿新 • • 發佈:2017-05-14
art arr 發的 array trace extends pan ava util
package duoxiancheng; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class TestQueue { public static void main(String[] args) { BlockingQueue<String> queue=new ArrayBlockingQueue<String>(10); new Save(queue).start();new Get(queue).start(); new Get(queue).start(); } } class Save extends Thread{ BlockingQueue<String> queue; static Object obj="hello"; static int i=0; public Save(BlockingQueue<String> queue) { super(); this.queue = queue; } public voidrun(){ while(true){ try { synchronized (obj) { queue.put("張飛"+i++); } Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } classGet extends Thread{ BlockingQueue<String> queue; public Get(BlockingQueue<String> queue) { super(); this.queue = queue; } public void run(){ int i=1; while(true){ try { System.out.println("隊列中的個數是"+queue.size()); System.out.println(Thread.currentThread().getName()+":"+queue.take()); Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
並發的集合類