多线程执行方法
1、
public void runExecutors(){
int coreCount = Runtime.getRuntime().availableProcessors();
int executeCount = 2 * coreCount; // 根据实际情况调整
ExecutorService executor = Executors.newFixedThreadPool(executeCount);
for (final xx x : xxx) {
executor.submit(new Runnable() {//如想获取值同步Future<?> future = executor.submit(new Runnable() {
@Override
public void run() {
执行方法;
}
});
}
//如想获取值同步 future.get();
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
2、
public void performTask() {
int coreCount = Runtime.getRuntime().availableProcessors();
int executeCount = 2 * coreCount; // 根据实际情况调整
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(executeCount);
// 提交一个异步任务
executor.submit(new Runnable() {
@Override
public void run() {
// 在这里执行异步任务
System.out.println("执行异步任务...");
// 模拟耗时操作
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步任务完成");
}
});
// 原始方法继续执行,不会等待异步任务完成
System.out.println("原始方法继续执行...");
// 关闭线程池
executor.shutdown();
}