展示一段最近学习的代码
ThreadPoolExecutor pool = new ThreadPoolExecutor(
1,
2,
1000,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(2),
Executors.defaultThreadFactory(),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// TODO
}
}
从 node 接触 kotlin, 再到 java ,总会接触到更多的知识点。
比如初始化连接池,定义错误处理器的时候,且其他地方也不会用到,这个时候就可以定义匿名内部类
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// TODO
}
}
我们可以看下这个 RejectedExecutionHandler 接口,只定义 rejectedExecution
这个方法
public interface RejectedExecutionHandler {
/**
* Method that may be invoked by a {@link ThreadPoolExecutor} when
* {@link ThreadPoolExecutor#execute execute} cannot accept a
* task. This may occur when no more threads or queue slots are
* available because their bounds would be exceeded, or upon
* shutdown of the Executor.
*
* <p>In the absence of other alternatives, the method may throw
* an unchecked {@link RejectedExecutionException}, which will be
* propagated to the caller of {@code execute}.
*
* @param r the runnable task requested to be executed
* @param executor the executor attempting to execute this task
* @throws RejectedExecutionException if there is no remedy
*/
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
在 java 8 后,则可以用更优雅的写法,比如用 lambda 的方式写
ThreadPoolExecutor pool = new ThreadPoolExecutor(1,
2,
1000,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(2),
Executors.defaultThreadFactory(),
(r, executor) -> {
// TODO
}
);
但用 lambda 的前提是 该接口定义了一个方法,java 编译系统才能正常的推导,多方法就用不了啦。
网友评论