1、两种实现方式
import java.util.concurrent.*;
public class TestSubmit {
public Future welcome1(String name, ExecutorService executor) {
System.out.println("方法调用线程名:" + Thread.currentThread().getName());
return executor.submit(() -> {
System.out.println("异步执行线程名:" + Thread.currentThread().getName()+",执行业务中...");
Thread.sleep(3000);
return "hello " + name;
});
}
public String welcome2(String name) throws ExecutionException, InterruptedException {
System.out.println("方法调用线程名:" + Thread.currentThread().getName());
FutureTask futureTask = new FutureTask<>(() -> {
System.out.println("异步执行线程名:" + Thread.currentThread().getName()+",执行业务中...");
Thread.sleep(3000);
return "hello " + name;
});
Thread t1 = new Thread(futureTask); //声明线程
t1.start();
return futureTask.get();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("程序主线程名称:" + Thread.currentThread().getName()+"任务开始...");
ExecutorService executor = Executors.newFixedThreadPool(10);
TestSubmit testSubmit = new TestSubmit();
Future result = testSubmit.welcome1("张明", executor);
System.out.println("程序主线程名称:" + Thread.currentThread().getName() + ",等待异步调用执行完中...");
System.out.println("程序主线程名称:" + Thread.currentThread().getName() +" 打印结果"+result.get());
executor.shutdown();
System.out.println();
System.out.println("---------------------------");
System.out.println();
String res =testSubmit.welcome2("王五");
System.out.println("程序主线程名称:" + Thread.currentThread().getName() + ",等待异步调用执行完中...");
System.out.println("程序主线程名称:" + Thread.currentThread().getName() +" 打印结果"+res);
}
}
2、输出结果
程序主线程名称:main任务开始... 方法调用线程名:main 程序主线程名称:main,等待异步调用执行完中... 异步执行线程名:pool-1-thread-1,执行业务中... 程序主线程名称:main 打印结果hello 张明 --------------------------- 方法调用线程名:main 异步执行线程名:Thread-0,执行业务中... 程序主线程名称:main,等待异步调用执行完中... 程序主线程名称:main 打印结果hello 王五



