public static class Student { String name; public Student() { } public Student(String name) { this.name = name; } public void println666() { System.out.println("666"); } public String getname() { return this.name; } } //创造固定线程池 private static ExecutorService executorService = Executors.newFixedThreadPool(20); public static void main(String[] args) { Student student = new Student(); /** * 无返回值线程池使用方法 * executorService 线程池 * student 学生类 */ executorService.execute(() -> student.println666()); /** * 有返回值使用方法 * executorService 线程池 * student 学生类 */ // CompletableFuture<>泛型为返回的参数getname 返回的是String // public String getname() { // return this.name; // } CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> { return student.getname(); }, executorService); //此时提示你需要抛异常try起来 try { //返回类型为调用方法的返回值 String name = stringCompletableFuture.get(); System.out.println(name); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
springBooot项目线池创建多线程
最新推荐文章于 2024-10-01 09:29:45 发布