如何在RejectedExecutionHandler中获取任务的字段?

时间:2017-11-16 09:30:45

标签: java multithreading concurrency threadpool

我想知道执行者拒绝的Task。例如,我想得到被拒绝任务的名称。但是在RejectedExecutionHandler中,我不能这样做!

这是我的代码:

public static void main(String[] args) throws Exception{
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            (Runnable r, ThreadPoolExecutor executor1) -> {
                //TODO 
                //want to get the task name 
                System.out.println("in reject:");
    });
    Task t1 = new Task("t1");
    Task t2 = new Task("t2");
    Future<Integer> t1Fe = executor.submit(t1);
    Future<Integer> t2Fe =  executor.submit(t2);

    System.out.println(t1Fe.get());
    System.out.println(t2Fe.get());
}

static class Task implements Callable{
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1);
        return name;
    }
}

1 个答案:

答案 0 :(得分:1)

我覆盖submit方法并覆盖FutureTask类!

public static void main(String[] args) throws Exception{
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            (Runnable r, ThreadPoolExecutor executor1) -> {
                //TODO
                //want to get the task name
                MyFutureTask task = (MyFutureTask)r;
                System.out.println("in reject:"+task.name);
    });
    Task t1 = new Task("t1");
    Task t2 = new Task("t2");
    Future<Integer> t1Fe = submit(executor,t1);
    Future<Integer> t2Fe =  submit(executor,t2);

    System.out.println(t1Fe.get());
    System.out.println(t2Fe.get());
}

public static Future submit(ThreadPoolExecutor executor,Callable task) {
    if (task == null) throw new NullPointerException();
    MyFutureTask ftask = new MyFutureTask(task);
    ftask.setName(((Task)task).name);
    executor.execute(ftask);
    return ftask;
}

static class MyFutureTask extends FutureTask{
    private String name;
    public MyFutureTask(Callable callable) {
        super(callable);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
static class Task implements Callable{
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1);
        return name;
    }
}