如何让BlockingQueue接受多种类型?
16lz
2021-01-22
I have class X
, class Y
and class Z
. If X
or Y
perform specific conditions, they should be put into BlockingQueue
. Class Z
just takes them from the queue.
我有类X,类Y和类Z.如果X或Y执行特定条件,它们应该被放入BlockingQueue。 Z类只从队列中取出它们。
I know that creating something like this:
我知道创建这样的东西:
BlockingQueue<X,Y> BQueue=new ArrayBlockingQueue<X,Y>(length);
is illegal. How to make it properly?
是非法的。如何使它正常?
2 个解决方案
#1
The simplest way is to allow the BlockingQueue
accept any object type:
最简单的方法是允许BlockingQueue接受任何对象类型:
BlockingQueue<Object> q = new ArrayBlockingQueue<>(length);
then, on take()
operation, you just look of what particular class the object is:
然后,在take()操作中,您只需查看该对象的特定类:
Object o = q.take();
if (o instanceof X) {
X x = (X) o;
// do work with x
} else if (o instanceof Y) {
Y y = (Y) o;
// do work with y
} else {
// o is neither X nor Y
}
If X
and Y
are inherited from common class or implement common interface, make your queue more specific:
如果X和Y继承自公共类或实现公共接口,请使您的队列更具体:
BlockingQueue<XYInterface> q = new ArrayBlockingQueue<>(length);
更多相关文章
- 如何知道Object是否为String类型对象?
- 如何将树路径转换为json对象
- OOP面向对象编程(一)-------方法的重载
- Java学习(三)面向对象之多态
- 黑马程序员——Java学习笔记 String类和基本数据类型对象包装类
- JAVA-初步认识-第十章-对象的初始化过程
- java类与对象,用程序解释
- 孔维滢201771010110《面向对象程序设计(java)》第一周学习总结
- Xstream把xml转换成java对象的异常:java.lang.NoClassDefFoundErr