发布于2021-06-12 14:58 阅读(486) 评论(0) 点赞(21) 收藏(3)
消费者消费消息它有一个工作池的概念,所以现在研究一下WorkPool的源码,看一看可以学到什么技巧。
这个实现是一个线程安全的类
WorkPool<K,W> K : 客户端类型, W : 工作项目类型
定义enqueueingCallback 的函数,入队工作项
public WorkPool(final int queueingTimeout) {
if (queueingTimeout > 0) {
this.enqueueingCallback = (queue, item) -> {
try {
boolean offered = queue.offer(item, queueingTimeout, TimeUnit.MILLISECONDS);
if (!offered) {
throw new WorkPoolFullException("Could not enqueue in work pool after " + queueingTimeout + " ms.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
} else {
this.enqueueingCallback = (queue, item) -> {
try {
queue.put(item);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
}
}
com.rabbitmq.client.impl.WorkPool#registerKey 注册客户类型(key)
com.rabbitmq.client.impl.WorkPool#limit 如果unlimited.isEmpty 时那么pool对于value的队列长度是1000
com.rabbitmq.client.impl.WorkPool#unlimit 如果unlimited.isNotEmpty 时那么pool对于value的队列长度是Integer.MAX_VALUE 【个人这个用boolean值不是很好,可能是后期扩展需要】
com.rabbitmq.client.impl.WorkPool#unregisterKey 注销客户类型(key) remove操作
com.rabbitmq.client.impl.WorkPool#unregisterAllKeys 注销所有客户类型(key) clear操作
com.rabbitmq.client.impl.WorkPool#nextWorkBlock (获取ready 客户端类型KEY, 对应queue的元素,最理想情况是拿到size的元素)
com.rabbitmq.client.impl.WorkPool#addWorkItem (添加工作项,pool必须存在对应客户端类型KEY,且添加ready队列中)
com.rabbitmq.client.impl.WorkPool#finishWorkBlock 判断是否完成工作块
public class JavaBiConsumer3 {
public static void main(String[] args) {
math(1, 1, (x, y) -> System.out.println(x + y)); // 2
math(1, 1, (x, y) -> System.out.println(x - y)); // 0
math(1, 1, (x, y) -> System.out.println(x * y)); // 1
math(1, 1, (x, y) -> System.out.println(x / y)); // 1
}
static <Integer> void math(Integer a1, Integer a2, BiConsumer<Integer, Integer> c) {
c.accept(a1, a2);
}
}
Map.forEach也有用到BiConsumer
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
下次使用两个对象进行相关操作可以使用BiConsumer
[Java 8 BiConsumer Examples](
原文链接:https://blog.csdn.net/m0_37355951/article/details/117717560
作者:我爱编程
链接:http://www.javaheidong.com/blog/article/222357/07395e5b54b3f84c6496/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!