Java中几种常用的队列
阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。同样,试图往已满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程使队列重新变得空闲起来,如从队列中移除一个或者多个元素,或者完全清空队列.
第一种:ConcurrentLinkedQueue,高性能无阻塞无界队列
代码demo:
1 ConcurrentLinkedQueue<String> q = new ConcurrentLinkedQueue<String>(); 2 q.offer("a"); 3 q.offer("b"); 4 q.offer("c"); 5 q.offer("d"); 6 q.add("e"); 7 8 System.out.println(q.poll()); //a 从头部取出元素,并从队列里删除 9 System.out.println(q.size()); //4 10 System.out.println(q.peek()); //b 11 System.out.println(q.size()); //4
第二种:ArrayBlockingQueue,基于数组的阻塞队列,有界队列
1 ArrayBlockingQueue<String> array = new ArrayBlockingQueue<String>(5); 2 array.put("a"); 3 array.put("b"); 4 array.add("c"); 5 array.add("d"); 6 array.add("e"); 7 //array.add("f"); 8 System.out.println(array.offer("a", 3, TimeUnit.SECONDS));
第三种:LinkedBlockingQueue,阻塞队列,无届队列
1 LinkedBlockingQueue<String> q = new LinkedBlockingQueue<String>(); 2 q.offer("a"); 3 q.offer("b"); 4 q.offer("c"); 5 q.offer("d"); 6 q.offer("e"); 7 q.add("f"); 8 //System.out.println(q.size()); 9 10 // for (Iterator iterator = q.iterator(); iterator.hasNext();) { 11 // String string = (String) iterator.next(); 12 // System.out.println(string); 13 // } 14 15 List<String> list = new ArrayList<String>(); 16 System.out.println(q.drainTo(list, 3)); 17 System.out.println(list.size()); 18 for (String string : list) { 19 System.out.println(string); 20 }
第四种:SynchronousQueue
1 final SynchronousQueue<String> q = new SynchronousQueue<String>(); 2 Thread t1 = new Thread(new Runnable() { 3 @Override 4 public void run() { 5 try { 6 System.out.println(q.take()); 7 } catch (InterruptedException e) { 8 e.printStackTrace(); 9 } 10 } 11 }); 12 t1.start(); 13 Thread t2 = new Thread(new Runnable() { 14 15 @Override 16 public void run() { 17 q.add("asdasd"); 18 } 19 }); 20 t2.start();