java线程池 —— 类继承结构及实现方式

类继承结构Executor类继承图

线程池创建

  • Executors
ExecutorService service = Executors.newFixedThreadPool(int nThreads);
ExecutorCompletionService completionService = new ExecutorCompletionService(service);
service.submit(...);
service.execute(...);

ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  • ThreadPoolExecutor
ThreadPoolExecutor executor = new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,  long keepAliveTime, TimeUnit unit,  BlockingQueue<Runnable> workQueue);
ThreadPoolExecutor executor = new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,  long keepAliveTime, TimeUnit unit,  BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory);
ThreadPoolExecutor executor = new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,  long keepAliveTime, TimeUnit unit,  BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler);
  • ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(int corePoolSize);
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory);
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler);
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler);

Runnable 和 Callable

public interface Callable<V> {
    V call() throws Exception;
}

public interface Runnable {
    public abstract void run();
}
  • 区别:
    a. Callable接口的call()方法可以有返回值(返回值通过Future接口获取),而Runnable接口的run()方法没有返回值。
    b. Callable接口的call()方法可以声明抛出异常,而Runnable接口的run()方法不可以。

猜你喜欢

转载自blog.csdn.net/qq_28376741/article/details/86741229