ThreadPoolTaskExecutor类可用来创建线程池并添加任务
1 TreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); 2 taskExecutor.setCorePoolSize(5);//设置核心线程数 3 taskExecutor.setMaxPollSize(10);//设置最大线程数 4 taskExecutor.setQueueCapacity(100);//设置队列容量 5 taskExecutor.initialize();//初始化线程池
使用TaskExecutor.execute()方法将任务提交到线程池中
1 taskExecutor.execute(new Runnable(){ 2 @Override 3 public void run(){ 4 //your task code here 5 } 6 });
可以使用submit()方法来提交Callable任务,并且可以获取返回值
1 Future<String> futureResult = taskExecutor.submit(new Callable<String>(){ 2 @Override 3 public String call() throws Exception{ 4 //your task code here 5 return "result"; 6 } 7 });
获取任务执行结果
String result = futureResult.get();
在应用程序关闭时,需要关闭线程池并等待所有任务完成
1 taskExecutor.shutdown(); 2 taskExecutor.awaitTermination(30,TimeUnit.SECONDS);//等待所有任务完成,最多30秒
ThreadPoolTaskExecutor的execute方法如何传递参数
ThreadPoolTaskExecutor的execute方法可以通过实现Runnable或Callable接口,来传递参数
实现Runnale接口时,可以将参数定义为类的成员变量,然后在run方法中使用
1 public class MyRunnable implements Runnable{ 2 private String param; 3 4 public MyRunnable(String param){ 5 this.param = param; 6 } 7 8 @Override 9 public void run(){ 10 //使用param参数 11 } 12 } 13 14 //在ThreadPoolTaskExecutor中执行 15 taskExecutor.executor(new MyRunnable("参数"));
实现Callable接口时,可以在泛型中指定返回值类型,并在call方法中返回结果。
public class MyCallable implements Callable<String>{ private String param; public MyCallable(String param){ this.param = param; } @Override public String call() throws Exception{ //使用param参数 return "结果"; } } //在TheadPoolTaskExecutor中执行 Future<String> future = taskExecutor.submit(new MyCallable("参数")); String result = future.get();//获取结果
标签:String,param,线程,taskExecutor,ThreadPoolTaskExecutor,public From: https://www.cnblogs.com/qian135811/p/17853991.html