1.继承Thread
2.实现Runnable
3
.
4
.
ExecutorServices提供了一个shutdownNow()和shutdown()的方法来关闭线程池。corePoolSize为5,需要运行的线程为10,所以将任务存储到队列中,不需要获取全局锁。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
比较:1.Thread类实现了Runnable接口,因此通常用Runnable接口创建线程
2.Runnable接口,提供了run()方法,无返回值,不能抛出异常。
3.Callable接口,提供了call()方法,有返回值,可以抛出异常。
4.运行Callable可以得到一个Future对象。Future得到结果。
5.FutureTask类实现了RunnableFuture接口,而RunnableFuture接口继承了Runnable和Future接口。
6.ExecutorService(接口)继承Executor(接口)。Executors此包中所定义的 Executor
、ExecutorService
、ScheduledExecutorService
、ThreadFactory
和 Callable
类的工厂和实用方法。