Java执行器没有排队任务的能力 [英] Java executor with no ability to queue tasks
本文介绍了Java执行器没有排队任务的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个Java执行器,如果其他任务正在处理,它会拒绝任务。我想不可能操作工作队列大小。
I need an Java executor that rejects tasks if some other task is processing. I guess it's not possible to get manipulating the working queue size.
有人可能会想知道为什么我需要一个具有这样的特性的执行器。我需要一个能够轻松更改策略并允许非零队列大小的功能。
Someone might wonder why I need an executor with such characteristic in the first place. I need an ability to easily change the policy and allow non-zero queue size.
任何想法?
推荐答案
使用 ThreadPoolExecutor 与 SynchronousQueue (复制自此答案)。
工作:
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SingleTaskExecutor {
public static void main(String[] args) {
try {
new SingleTaskExecutor().runTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public void runTest() throws Exception {
ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
tp.setRejectedExecutionHandler(new RejectedTaskHandler());
final Semaphore oneTaskDone = new Semaphore(0);
tp.execute(new Runnable() {
@Override public void run() {
System.out.println("Sleeping");
try { Thread.sleep(300); } catch (Exception e) { e.printStackTrace();}
System.out.println("Done sleeping");
oneTaskDone.release();
}
});
tp.execute(new Runnable() {
@Override public void run() { System.out.println("Never happends"); }
@Override public String toString() { return "Rejected Runnable"; }
});
oneTaskDone.acquire();
tp.execute(new Runnable() {
@Override public void run() { System.out.println("Running"); }
});
tp.shutdown();
tp.awaitTermination(100, TimeUnit.MILLISECONDS);
System.out.println("Finished");
}
static class RejectedTaskHandler implements RejectedExecutionHandler {
@Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("Task rejected: " + r);
}
}
}
这篇关于Java执行器没有排队任务的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文