背景
当我们使用IDEA时,经常出现下图的灰色警告,看着很不雅,老觉得自己是不是写的不规范,显得逼格不够高。出现如下情况呢,是因为当前使用的jdk版本有更简单的表达式可以代替。
问题
代码如下:
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(3);
//创建一个Callable,3秒后返回String类型
Callable myCallable = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println("call方法执行了");
return "call方法返回值";
}
};
System.out.println("提交任务之前 " + LocalDateTime.now().toLocalTime());
Future future = executor.submit(myCallable);
System.out.println("提交任务之后,获取结果之前 " + LocalDateTime.now().toLocalTime());
System.out.println("获取返回值: " + future.get());
System.out.println("获取到结果之后 " + LocalDateTime.now().toLocalTime());
}
解决方案
既然IDEA都给出了警告提示,相信IDEA这么强大的工具肯定也是有了解决方案。接下来就让我们使用神奇的万能快捷键吧
Alt + Enter
优化后:
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(2);
//创建一个Callable,3秒后返回String类型
Callable myCallable = () -> {
Thread.sleep(3000);
System.out.println("call方法执行了");
return "call方法返回值";
};
System.out.println("提交任务之前 " + LocalDateTime.now().toLocalTime());
Future future = executor.submit(myCallable);
System.out.println("提交任务之后,获取结果之前 " + LocalDateTime.now().toLocalTime());
System.out.println("获取返回值: " + future.get());
System.out.println("获取到结果之后 " + LocalDateTime.now().toLocalTime());
}
结束语
通过以上的问题,充分体现了快捷键的重要性,正所谓学会kkj,走遍天下都不怕。当然在技术的不断进步中,追求技术的完美也是不可或缺的一点。