带有示例的Java.util.concurrent.Executor 接口
Java中的并发 API 提供了一种称为执行器的功能,它启动和控制线程的执行。因此,执行程序提供了使用线程类管理线程的替代方法。 Executor 的核心是Executor接口。它是指执行已提交的 Runnable 任务的对象。
类层次结构:
java.util.concurrent
↳ Interface Executor
实现子接口:
ExecutorService
ScheduledExecutorService
实现类:
AbstractExecutorService
ForkJoinPool
ScheduledThreadPoolExecutor
ThreadPoolExecutor
Executor 接口中的方法:
- execute() :此函数在将来的某个时间执行给定的命令。根据 Executor 实现的判断,该命令可以在新线程、池线程或调用线程中执行。
句法:
void execute(Runnable task)
演示 Executor 的示例。
Java
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
public class ExecutorDemo {
public static void main(String[] args)
{
ExecutorImp obj = new ExecutorImp();
try {
obj.execute(new NewThread());
}
catch (RejectedExecutionException
| NullPointerException exception) {
System.out.println(exception);
}
}
}
class ExecutorImp implements Executor {
@Override
public void execute(Runnable command)
{
new Thread(command).start();
}
}
class NewThread implements Runnable {
@Override
public void run()
{
System.out.println("Thread executed under an executor");
}
}
输出:
Thread executed under an executor
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/concurrent/Executor.html