首页 > 代码库 > ThreadPoolExecutor
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。