1.LinkedBlockingDeque
public class LinkedBlockingDeque<E> extends AbstractQueue<E> implements BlockingDeque<E>, Serializable
2.主要方法
- takeFirst()和takeLast():分別返回類表中第一個和最后一個元素,返回的元素會從類表中移除。如果列表為空,調用的方法的線程將會被阻塞直達列表中有可用元素。
- getFirst()和getLast():分別返回類表中第一個和最后一個元素,返回的元素不會從列表中移除。如果列表為空,則拋出NoSuckElementException異常。
- peek()、peekFirst()和peekLast():分別返回列表中第一個元素和最后一個元素,返回元素不會被移除。如果列表為空返回null.
- poll()、pollFirst()和pollLast():分別返回類表中第一個和最后一個元素,返回的元素會從列表中移除。如果列表為空,返回Null。
public class Client implements Runnable { private LinkedBlockingDeque<String> requestList; public Client(LinkedBlockingDeque<String> requestList) { super(); this.requestList = requestList; } @Override public void run() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { StringBuilder request = new StringBuilder(); request.append(i); request.append(":"); request.append(j); try { requestList.put(request.toString()); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Clint: " + request + " " + new Date()); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Client: End"); } }
public class LinkedBlockingDequeMain { public static void main(String[] args) throws Exception { LinkedBlockingDeque<String> list=new LinkedBlockingDeque<String>(3); Client client=new Client(list); Thread thread=new Thread(client); thread.start(); for (int i = 0; i <5; i++) { for (int j =0; j <3; j++) { String request=list.take(); System.out.println("Main:Request:"+request+" at "+new Date()+" Size "+list.size()); } TimeUnit.MILLISECONDS.sleep(300); } System.out.println("Main:End"); } }