注:这是我很久之前在博客里面看到的,忘记是哪一篇了,分享一下
测试响应耗时
private String test1() {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "test1";}private String test2() {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "test2";}private String test3() {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "test3";}private String test4() {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "test4";}public static void main(String[] args) throws InterruptedException {test test=new test();long startTime=System.currentTimeMillis();List<String> list=new ArrayList<>(4);list.add(test.test1());list.add(test.test2());list.add(test.test3());list.add(test.test4());System.out.println("耗时:"+(System.currentTimeMillis()-startTime)+"ms");}
可以看到输出后的响应耗时
我们再使用ExecutorService 来测试一下响应耗时
public static void main(String[] args) throws InterruptedException {test test=new test();long startTime=System.currentTimeMillis();/*** IO密集型建议:2*CPU,因为IO密集型线程不是一直在运行,所以可以配置多一点;* CPU密集型建议:因为一直在使用CPU,所以要保证线程数不能太多,可以CPU数+1;*/ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1);Future<String> test1Future=executorService.submit(() -> {if (false) {throw new RuntimeException("创建线程失败~");} else {return test.test1();}});Future<String> test2Future=executorService.submit(() -> {if (false) {throw new RuntimeException("创建线程失败~");} else {return test.test2();}});Future<String> test3Future=executorService.submit(() -> {if (false) {throw new RuntimeException("创建线程失败~");} else {return test.test3();}});Future<String> test4Future=executorService.submit(() -> {if (false) {throw new RuntimeException("创建线程失败~");} else {return test.test4();}});List<Future<String>> futureList= Arrays.asList(test1Future,test2Future,test3Future,test4Future);List<String> list=futureList.stream().map(future ->{try {System.out.println(future.get());return future.get();} catch (Exception e) {return null;}}).collect(Collectors.toList());//任务执行完将ExecutorService置于已关闭状态,不允许再提交新的任务executorService.shutdown();//确保所有任务都已完成或已被取消。这个方法会使当前线程等待,直到所有任务都已完成或者超出了指定的时间限制executorService.awaitTermination(60, TimeUnit.SECONDS);// List<String> list=new ArrayList<>(4);
// list.add(test.test1());
// list.add(test.test2());
// list.add(test.test3());
// list.add(test.test4());System.out.println("耗时:"+(System.currentTimeMillis()-startTime)+"ms");}