一,常用方法
二,案例
package XianChengChildren;
import java.util.concurrent.*;
public class ThewadPoolTest1 {
public static void main(String[] args) throws Exception {
// ExecutorService pool = new ThreadPoolExecutor(3,5,8,
// TimeUnit.SECONDS,
// new LinkedBlockingQueue<>(4),
// Executors.defaultThreadFactory(),
// new ThreadPoolExecutor.AbortPolicy());
//1,通过Executors创建一个线程池对象
ExecutorService pool = Executors.newFixedThreadPool(3);
//注意:核心线程数量应=CPU的核数+1(计算密集型任务);CPU的核数*2(IO密集型任务)
//例如;我的电脑为32核;计算密集型任务应填33,IO密集型任务应填64
//Ctrl键+Alt键+Dcl键打开任务管理器查看性能逻辑处理器为CPU内核
Future<String> f1 = pool.submit(new MyRunnable(100));
Future<String> f2 = pool.submit(new MyRunnable(200));
Future<String> f3 = pool.submit(new MyRunnable(300));
Future<String> f4 = pool.submit(new MyRunnable(400));
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
}
}
package XianChengChildren;
import java.util.concurrent.Callable;
public class MyRunnable implements Callable {
private int n;
public MyRunnable(int n) {
this.n = n;
}
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 0; i <=n ; i++) {
sum+=1;
}
return Thread.currentThread().getName()+"线程求出了1-"+n+"的和是"+sum;
}
}
3,注意大型应用不能用Executors