java.util.concurrent JDK线程池 使用
使用JDK的线程池心得
这里使用的是 java.util.concurrent 包中的线程池。该包中所有方法都是线程安全的。
Executors.newCachedThreadPool();
API:创建一个可根据需要创建新线程的线程池。 如果想自己设置线程池的参数可以使用使用 :
ThreadPoolExecutor(int corePoolSize,int maximumPoolSize, long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable>workQueue)
参数:
corePoolSize - 池中所保存的线程数,包括空闲线程。
maximumPoolSize - 池中允许的最大线程数。
keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
unit - keepAliveTime 参数的时间单位。
workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务
目标方法:
需要实现Callable接口
public class TestCollable implements Callable<String>{
private String result ;
public TestCollable(String result){
this.result = result;
}
@Override
public String call() throws Exception {
System.out.println("开始执行任务----"+Thread.currentThread().getName());
System.out.println("任务: "+result);
System.out.println("结束任务----"+Thread.currentThread().getName());
return "bb";
}
}
使用线程池 多线程调用目标方法
@Test
public void testCall() throws InterruptedException, ExecutionException{
//newCachedThreadPool() 创建一个可根据需要创建新线程的线程池
ExecutorService executorService = Executors.newCachedThreadPool();
//调用get()方法程序将会阻塞 直到目标方法有返回值或者抛异常
for(int i=0 ; i<5 ;i++){
System.out.println(executorService.submit(new TestCollable("aa")).get());
}
}
}
执行结果:
开始任务----pool-1-thread-1
任务: aa
任务结束----pool-1-thread-1
bb
开始任务----pool-1-thread-2
任务: aa
任务结束----pool-1-thread-2
bb
由此可以看出 executorService.submit(new TestCollable("aa")).get()); 方法阻塞了程序 直到有结果返回
将执行结果放入list观察 统一输出结果 不再阻塞程序
@Test
public void testCall() throws InterruptedException, ExecutionException{
ExecutorService executorService = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for(int i=0 ; i<5 ;i++){
results.add(executorService.submit(new TestCollable("aa")));
}
for(Future<String> fs:results){
System.out.println(fs.get());
}
}
程序执行结果
开始任务----pool-1-thread-1
开始任务----pool-1-thread-2
任务: aa
任务结束----pool-1-thread-2
任务: aa
任务结束----pool-1-thread-1
bb
bb
开始任务----pool-1-thread-3
任务: aa
任务结束----pool-1-thread-3
bb
开始任务----pool-1-thread-4
任务: aa
任务结束----pool-1-thread-4
bb
开始任务----pool-1-thread-5
任务: aa
任务结束----pool-1-thread-5
bb