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"); } }
时间: 2024-11-07 21:26:43