1 回答
TA贡献1831条经验 获得超4个赞
您可以使用条件变量来完成此操作。
final ReentrantLock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
private void waitForInput() {
lock.lock();
Listener.msgEvnt = null;
try {
while (Listener.msgEvnt == null)
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
lock.lock();
try {
Listener.msgEvnt = msgEvnt;
condition.signal();
} finally {
lock.unlock();
}
}
请参阅可重入锁和条件
您可以使用阻塞队列
final BlockingQueue queue = new ConcurrentBlockingQueue();
private MessageReceivedEvent waitForInput() throws InterruptedException {
return queue.take();
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
queue.put(event);
}
您可以使用Callback,这是我推荐的。
Consumer<? super MessageReceivedEvent> callback;
private void onInput(Consumer<? super MessageReceivedEvent> callback) {
this.callback = callback;
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
if (this.callback != null)
this.callback.accept(event);
this.callback = null;
}
使用示例:
listener.waitForInput(event -> {
System.out.printf("%#s: %s\n", event.getAuthor(), event.getMessage().getContentDisplay());
});
添加回答
举报