多线程实现方式1:https://blog.csdn.net/qq_39849328/article/details/103303432
多线程之通过completableFuture实现多线程:
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
public class CompletableFutureStudyFun1 {
private volatile Integer baseNum = 1;
AtomicInteger counter = new AtomicInteger(0);
@Test
public void executorServiceTestService() {
List<CompletableFuture<Integer>> futureList = Lists.newArrayList();
//创建线程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 3, 4, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder().setNameFormat("service_test").build(), new ThreadPoolExecutor.AbortPolicy());
//通过completableFuture,循环调用资源。
for (int i = 0; i<10; i++) {
final int per = i==0 ? 1 : i;
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getSumForParam(per), threadPoolExecutor);
//无需等待结果,主线程继续执行。
futureList.add(future);
}
//获得返回结果
List<Integer> futureCallBack = Lists.newArrayList();
futureList.stream().forEach(future -> {
try {
//获得线程返回值。
int res = future.exceptionally(e -> { return null;}).get(60, TimeUnit.SECONDS);
//添加到线程结果列表
futureCallBack.add(res);
System.out.println("=======>>>>>>>>>>>>>>"+res);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
});
//循环打印
futureCallBack.stream().forEach(System.out::println);
//用于debug查看各个参数值,判断实现情况
System.out.println("================");
}
/**
* @description 多线程执行方法。
* @param per
* @return
* @eg synchronized保证参数有序性,并且尝试使用cas
*/
public /*synchronized*/ int getSumForParam(int per) {
//System.out.print( counter.incrementAndGet() + " ");
return baseNum++;
}
}
作者原创:仅用于学习分享和记录,请求转载。