gpt4 book ai didi

java - ThreadPoolExecutor 检查某个任务是否在队列中

转载 作者:行者123 更新时间:2023-11-29 04:44:56 26 4
gpt4 key购买 nike

我有一个只能由单个线程使用的串行连接。但是在我向执行者提交新任务之前,我想检查该特定任务是否已经在队列中(例如轮询值)。

executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
new Thread(new Runnable() {

@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
TaskRunnable runn = new TaskRunnable(
Integer.toString(i), "42");
if (!executor.getQueue().contains(runn)) {
executor.submit(runn);
}
}
}
}
}).start();


public void write(String addr, String value) {
// write
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

class TaskRunnable implements Runnable {
String addr, value;

public TaskRunnable(String addr, String value) {
this.addr = addr;
this.value = value;
}

@Override
public void run() {
write(addr, value);
System.out.println("Executed: " + addr + " - "
+ executor.getQueue().size());
}

@Override
public boolean equals(Object obj) {
TaskRunnable other = (TaskRunnable) obj;
return this.addr.equals(other.addr);
}

@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.addr != null ? this.addr.hashCode() : 0);
return hash;
}

}

如果我检查 executor.getQueue()类型是 BlockingQueue<Runnable>但如果我这样做 executor.getQueue().contains(task) TaskRunnable 的 equals 方法使用 FutureTask 类型的对象调用我得到了这个异常(exception)

java.util.concurrent.FutureTask cannot be cast to ExecutorTest$TaskRunnable

知道如何检查某个 TaskRunnable已经在队列中了吗?

最佳答案

您需要存储从 executor.submit(runn); 返回的 Future。然后您可以询问队列是否包含 Future。

关于java - ThreadPoolExecutor 检查某个任务是否在队列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37585355/

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