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

类继承结构java线程池 —— 类继承结构及实现方式_第1张图片

线程池创建

  • 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 workQueue);
ThreadPoolExecutor executor = new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,  long keepAliveTime, TimeUnit unit,  BlockingQueue workQueue, ThreadFactory threadFactory);
ThreadPoolExecutor executor = new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,  long keepAliveTime, TimeUnit unit,  BlockingQueue 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 call() throws Exception;
}

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

你可能感兴趣的:(java基础学习笔记)