ThreadPoolExecutor检查某个Task是否在队列中

时间:2016-06-02 07:29:59

标签: java future executorservice threadpoolexecutor futuretask

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

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的等于方法我得到了这个例外

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

任何想法如何检查队列中是否已有某个TaskRunnable

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

executor.submit(Runnable)替换为executor.execute(Runnable);,然后不应将Runnable重新打包到自己的任务中。