10 Java并发编程5-线程池的使用
2017-01-24 14:09
916 查看
http://www.cnblogs.com/dolphin0520/p/3932921.html
一 Java中的ThreadPoolExecutor类
java.util.concurrent.ThreadPoolExecutor类线程池中最核心的一个类。
1)Executor是一个顶层接口,只有一个void execute(Runnable)方法,执行传进去的任务。
2)ExecutorService接口继承了Executor接口,并声明了一些方法:submit\invokeAll\invokeAny\shutDown。
3)抽象类AbstractExecutorService实现了ExecutorService接口。
4)ThreadPoolExecutor继承了类AbstractExecutorService。
ThreadPoolExecutor类中几个重要的方法:
1)execute() : 向线程池提交一个任务,交由线程池去执行。
2)submit():向线程池提交任务,能返回Future,底层调用execute()。
3)shutdown():关闭线程池
4)shutdownNow()
二 深入剖析线程池实现原理
三 使用示例
不提倡直接使用ThreadPoolExecutor,而是使用Executors类中提供的几个静态方法来创建线程池。
四 如何合理配置线程池的大小
如果是CPU密集型任务,就需要尽量压榨CPU,参考值可以设为 NCPU+1
如果是IO密集型任务,参考值可以设置为2*NCPU
一 Java中的ThreadPoolExecutor类
java.util.concurrent.ThreadPoolExecutor类线程池中最核心的一个类。
1)Executor是一个顶层接口,只有一个void execute(Runnable)方法,执行传进去的任务。
2)ExecutorService接口继承了Executor接口,并声明了一些方法:submit\invokeAll\invokeAny\shutDown。
3)抽象类AbstractExecutorService实现了ExecutorService接口。
4)ThreadPoolExecutor继承了类AbstractExecutorService。
ThreadPoolExecutor类中几个重要的方法:
1)execute() : 向线程池提交一个任务,交由线程池去执行。
2)submit():向线程池提交任务,能返回Future,底层调用execute()。
3)shutdown():关闭线程池
4)shutdownNow()
二 深入剖析线程池实现原理
三 使用示例
package javaconfig; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ExecutorTest { public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); pool.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println("execute执行"); } }); Future<Integer> submit = pool.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub return 1; } }); try { Integer integer = submit.get(); System.out.println("submit执行:" + integer); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } pool.shutdown(); } }
不提倡直接使用ThreadPoolExecutor,而是使用Executors类中提供的几个静态方法来创建线程池。
四 如何合理配置线程池的大小
如果是CPU密集型任务,就需要尽量压榨CPU,参考值可以设为 NCPU+1
如果是IO密集型任务,参考值可以设置为2*NCPU
相关文章推荐
- Java并发编程:线程池的使用
- java并发编程:线程池的使用
- Java 并发编程之线程池的使用
- Java并发编程:线程池的使用
- Java并发编程:线程池的使用
- Java并发编程:线程池的使用
- Java 并发编程之线程池的使用 (二)
- (转)Java并发编程:线程池的使用方法
- Java 并发编程之线程池的使用 (三)
- Java并发编程:线程池的使用
- Java并发编程:线程池的使用
- Java并发编程:线程池的使用
- Java 并发编程之线程池的使用 (三)
- Java并发编程:线程池的使用
- Java并发编程:线程池的使用
- Java并发编程:线程池的使用
- java并发编程-线程池的使用
- Java 并发编程之线程池的使用(一)
- Java并发编程之线程池的理解与使用
- Java并发编程:线程池的使用