Callable实现多线程
和Thread,Runnable实现多线程的区别
示例
import java.util.concurrent.*;
public class CallableExample01 implements Callable<Boolean> {
//执行体
public Boolean call() throws Exception {
System.out.println("执行的线程为:" + Thread.currentThread().getName());
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableExample01 c1 = new CallableExample01();
CallableExample01 c2 = new CallableExample01();
CallableExample01 c3 = new CallableExample01();
//1 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//2 提交执行
Future<Boolean> f1 = ser.submit(c1);
Future<Boolean> f2 = ser.submit(c2);
Future<Boolean> f3 = ser.submit(c3);
//3 获取结果
boolean res = f1.get();
boolean res1 = f2.get();
boolean res2 = f3.get();
//4 关闭服务
ser.shutdownNow();
}
执行结果
执行的线程为:pool-1-thread-1
执行的线程为:pool-1-thread-2
执行的线程为:pool-1-thread-3
原文:https://www.cnblogs.com/lanxinren/p/14674550.html