作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道被执行者拒绝的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/
我是一名优秀的程序员,十分优秀!