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

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的对象调用FutureTask的equals方法,并且出现此异常

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


知道如何检查队列中是否已存在某个TaskRunnable吗?

最佳答案

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

10-08 16:51