gpt4 book ai didi

java - BlockingQueue.peekWait()

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:13 25 4
gpt4 key购买 nike

我有一种情况需要 BlockingQueue 上的方法 peekWait。我会将此方法描述为

retrieves but not remove the head of the queue, waiting if necessary until an element becomes available

我在 BlockingQueue LinkedBlockingQueue 上看不到相应的方法。这是否存在或我可以以某种方式做到这一点?我考虑过执行 poll() + addFirst() 但队列可能会在中间填满,让我陷入困境。

最佳答案

将调用包装到 BlockingQueue#peek()Callable ,执行它并等待 Future<T>.get(long, TimeUnit) :

final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
ExecutorService executor = Executors.newCachedThreadPool();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

scheduler.schedule(new Runnable()
{
@Override
public void run()
{
String e = UUID.randomUUID().toString();
System.out.println("adding = " + e);
queue.add(e);
}
}, 2, TimeUnit.SECONDS);

Callable<String> task = new Callable<String>()
{
@Override
public String call() throws Exception
{
String result = null;
while ((result = queue.peek()) == null)
{
Thread.sleep(100L);
}
return result;
}
};

String peeked = null;
try
{
peeked = executor.submit(task).get(1, TimeUnit.SECONDS);
System.out.println("this should never be printed");
queue.poll();
}
catch (TimeoutException e)
{
System.out.println("null: peeked = " + peeked);
e.printStackTrace();
}

try
{
peeked = executor.submit(task).get(2, TimeUnit.SECONDS);
System.out.println("not null: peeked = " + peeked);
}
catch (TimeoutException e)
{
e.printStackTrace();
System.out.println("should not throw an exception");
}

关于java - BlockingQueue.peekWait(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6815204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com