我有类X
,类Y
和类Z
。如果X
或Y
执行特定条件,则应将其放入BlockingQueue
中。Z
类只是从队列中取走。
我知道创建类似的东西:
BlockingQueue<X,Y> BQueue=new ArrayBlockingQueue<X,Y>(length);
是非法的。如何正确做到?
您可以做Sasha提出的事情并使用BlockingQueue<Object>
,但我更喜欢将共同功能声明为接口,然后使每个类搬运它的功能,而不是使用instanceof
声明:
public interface Common {
boolean shouldEnqueue();
void doSomething();
}
public class X implements Common {
public boolean shouldEnqueue() {
...
}
public void doSomething() {
System.out.println("This is X");
}
}
public class Y implements Common {
public boolean shouldEnqueue() {
...
}
public void doSomething() {
System.out.println("This is Y");
}
}
public class Producer {
private final BlockingQueue<Common> queue;
void maybeEnqueue(Common c) {
if(c.shouldEnqueue()) {
queue.add(c);
}
}
}
public class Consumer {
private final BlockingQueue<Common> queue;
void doSomething() {
queue.take().doSomething();
}
}
最简单的方法是允许BlockingQueue
接受任何对象类型:
BlockingQueue<Object> q = new ArrayBlockingQueue<>(length);
然后,在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
}
如果X
和Y
是从普通类继承或实现共同接口的,请使您的队列更具体:
BlockingQueue<XYInterface> q = new ArrayBlockingQueue<>(length);