gpt4 book ai didi

java - 如何让BlockingQueue接受多种类型?

转载 作者:行者123 更新时间:2023-12-02 04:41:03 25 4
gpt4 key购买 nike

我有类X、类Y和类Z。如果XY执行特定条件,则应将它们放入BlockingQueue中。 Z 类只是从队列中取出它们。

我知道创建这样的东西:

BlockingQueue<X,Y> BQueue=new ArrayBlockingQueue<X,Y>(length);

是非法的。如何正确制作?

最佳答案

您可以按照 Sasha 的建议进行操作并使用 BlockingQueue<Object>但我更喜欢将通用功能声明到接口(interface)中,然后让每个类处理它自己的功能,而不是使用 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();
}
}

关于java - 如何让BlockingQueue接受多种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com