public class MyCallable implements Callable<String> { private String username; private long sleepValue; public MyCallable(String username, long sleepValue) { this.username = username; this.sleepValue = sleepValue; } @Override public String call() throws Exception { //当 System.out.println(username); Thread.sleep(sleepValue); // if ("userName3".equals(username)){ // throw new Exception("自己抛出异常了"); // } return "return: "+ username; }} @Test public void testMyCallable() throws InterruptedException { try { List<MyCallable> list = new ArrayList<>(); for (int i=1; i<=5; i++){ MyCallable myCallable = new MyCallable("userName"+i, i*1000); list.add(myCallable); } //手动线程数 最大线程 当多少时后面线程进行排队 ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10,5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()); //自动处理线程 ExecutorService executor = Executors.newCachedThreadPool(); CompletionService completionService = new ExecutorCompletionService(executor); for (int i=0; i<5; i++){ completionService.submit(list.get(i)); } //处理完结束 executor.shutdown(); //谁先完成谁出 for (int i=0; i<5; i++){ System.out.println("等待打印"+(i+1)+"个返回值"); System.out.println(completionService.take().get()); } //怎么放进去怎么出 for (int i=0; i<5; i++){ System.out.println("一个一个等待返回结果: " + completionService.get(i).get()); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } //实际开发对多线程进行封装 只负责调用 方法与实例分开 package com.util.common; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; public class ThreadUtil implements Callable<Object> { private Object task; public Object getTask() { return task; } public void setTask(Object task) { this.task = task; } @Override public Object call() throws Exception { return getTask(); } public static void main(String[] args) { try { List<ThreadUtil> list = new ArrayList<>(); for (int i=1; i<=5; i++){ ThreadUtil threadUtil = new ThreadUtil(); //方法 ThreadUtil p= new ThreadUtil(); threadUtil.setTask(p.getStr(i)); list.add(threadUtil); } //手动 ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10,5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()); //内置 //ExecutorService executorService = Executors.newCachedThreadPool(); CompletionService completionService = new ExecutorCompletionService(executor); //运行任务 for(int i=0;i<list.size();i++){ completionService.submit(list.get(i)); } //运行完关闭 executor.shutdown(); //谁先出 先取 System.out.println("谁先出 先取"); for(int i=0;i<list.size();i++){ System.out.println(completionService.take().get()); } System.out.println("按顺序取"); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).getTask()); } } catch (Exception e) { e.printStackTrace(); } } //模拟任务 public int getStr(int str) { try{ System.out.println("传值:"+str); int r=new Random().nextInt(400)+1000; Thread.sleep(r); }catch (Exception e){ } return str; } }
关注"都市百货" 了解南陵
微信咨询wanglf2r(不拉群 发广告者勿加)
热门评论