ThreadPoolExecutor
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThreadPoolExecutor相关的知识,希望对你有一定的参考价值。
1 package concurrency; 2 3 import java.util.List; 4 import java.util.concurrent.BlockingQueue; 5 import java.util.concurrent.Callable; 6 import java.util.concurrent.ExecutionException; 7 import java.util.concurrent.Future; 8 import java.util.concurrent.LinkedBlockingQueue; 9 import java.util.concurrent.ThreadPoolExecutor; 10 import java.util.concurrent.TimeUnit; 11 12 public class ThreadPoolTest { 13 //定义任务队列 14 private static BlockingQueue<Runnable> workQueue =new LinkedBlockingQueue<Runnable>(); 15 //创建线程池 16 private static ThreadPoolExecutor executor = 17 new ThreadPoolExecutor(10, 25, 1000000, TimeUnit.NANOSECONDS, workQueue); 18 public static void main(String[] args) throws InterruptedException, ExecutionException { 19 //execute()方法用于提交不需要返回值的任务 20 executor.execute(new ThreadPoolJob()); 21 22 //submit 方法用于提交需要返回值的任务 23 executor.submit(new ThreadPoolJob());//可以提交Runnable类型的job 24 25 Future<String> future = executor.submit(new ThreadPoolCalJob());//也可以提交Callable类型的job 26 String result = future.get();//Future.get()会一直阻塞到job完成并返回结果 27 28 System.out.println("result=" + result); 29 30 executor.shutdown();//将线程池状态设置为shutdown,并中断所有没有正在执行任务的线程 31 32 //List<Runnable> jobs = executor.shutdownNow();//将线程池的状态设置为stoped,并尝试停止所有正在执行或者暂停任务的线程,并返回等待执行任务的列表 33 } 34 35 } 36 class ThreadPoolJob implements Runnable{ 37 38 @Override 39 public void run() { 40 System.out.println("i am a runnable.."); 41 } 42 43 } 44 45 class ThreadPoolCalJob implements Callable<String>{ 46 47 @Override 48 public String call() throws Exception { 49 System.out.println("submit a callable"); 50 Thread.sleep(3000); 51 return "ThreadPoolCalJob return a callable"; 52 } 53 54 }
以上是关于ThreadPoolExecutor的主要内容,如果未能解决你的问题,请参考以下文章
聊聊高并发(四十)解析java.util.concurrent各个组件(十六) ThreadPoolExecutor源代码分析
ThreadPoolExecutor().map 与 ThreadPoolExecutor().submit 有何不同?
Java中的线程池——ThreadPoolExecutor源代码分析
JDK1.7中的ThreadPoolExecutor源代码剖析