gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:22:48 26 4
gpt4 key购买 nike

我想知道被执行者拒绝的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;
}
}

最佳答案

我覆盖了 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;
}
}

关于java - 如何在 RejectedExecutionHandler 中获取任务的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47325987/

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