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()方法不可以。