步骤:
创建线程池对象
创建 Callable 接口子类对象
提交 Callable 接口子类对象
关闭线程池
实例:
class TaskCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
return null;
}
}
public class ThreadPoolOfCallable {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
TaskCallable c = new TaskCallable();
TaskCallable c1 = new TaskCallable();
//线程池中获取线程对象,调用run方法
service.submit(c);
//再获取一个
service.submit(c1);
//关闭线程池
service.shutdown();
}
}
---------------------
原文地址:https://www.cnblogs.com/liyanyan665/p/11359760.html
时间: 2024-11-10 23:16:43