如何使Blockingqueue接受多种类型



我有类X,类Y和类Z。如果XY执行特定条件,则应将其放入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
}

如果XY是从普通类继承或实现共同接口的,请使您的队列更具体:

BlockingQueue<XYInterface> q = new ArrayBlockingQueue<>(length);

最新更新