import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import com.google.common.collect.Queues; public class T { public static void main(String[] args) { final BlockingQueue<Long> q = new LinkedBlockingQueue<Long>(); new Thread(new Runnable(){ public void run() { Random r = new Random(1); long num=1L; while(true) { try { System.out.println(num); q.put(num); num++; Thread.sleep(r.nextInt(10)); } catch (InterruptedException e) { e.printStackTrace(); } } }}).start(); while (true) { try { List<Long> l = new ArrayList<Long>(10); Queues.drain(q, l, 10, 5, TimeUnit.SECONDS); System.out.println(l); } catch (InterruptedException e) { e.printStackTrace(); } } } }
用guava的Queues.drain 解决 按数量和指定时间 弹出队列中的元素
最新推荐文章于 2023-10-07 15:54:16 发布