首先可以用线程池定义多个线程。
// 静态化避免重复创建,初始化10个线程
private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public void test() {
//这里是封装的类,该类实现Runnable接口
Test task = new Test();
//通过线程池对象执行该方法
executor.execute(task);
}
class Test implements Runnable{
//定义好参数
private String A;
private String B;
//再定义一个构造器
public Test(String A,String B){
this.A=A;
this.B=B;
}
@Override
public void run() {
//这里就是写线程执行的方法了。异步代码大致就形成了,这样可以提高效率当接口返回时间较慢时候。
}
另外多线程我发现可以用来优化for循环语句,如果当for循环里面嵌套了多层循环,可以尝试用stream流以及多线程来优化,提高执行效率,反正多线程跟和stream流yyds。
if (CollectionUtils.isNotEmpty(list)) {
int listSize = list.size();
// 子线程计数器
CountDownLatch childThreadCountDownLatch = new CountDownLatch(listSize);
for (User record : list) {
executor.execute(() -> {
try {
User user= userService.getDetails(record.getUser(), record.getName(), startDay, endDay);
} catch (Exception e) {
e.printStackTrace();
logger.error("查询发生异常,异常内容:{}", e.getMessage());
} finally {
//线程任务完成后
childThreadCountDownLatch.countDown();
}
});
}
try {
childThreadCountDownLatch.await();// 主线程在阻塞,等待线程执行完成
} catch (InterruptedException e) {
e.printStackTrace();
}
//定义线程池最大容量5个线程
private static final ExecutorService executor = Executors.newFixedThreadPool(5);
/**
* @param args
*/
public static void main(String[] args) {
final int[] tickets = {70};
CountDownLatch countDownLatch = new CountDownLatch(tickets.length);
//模拟60个客户买票,由五个线程去完成
for (int i = 60; i > 0; i--) {
executor.execute(() -> {
while (true) {
try {
if (tickets[0] > 0) {
System.out.println(Thread.currentThread().getName() + "出售票" + tickets[0]--);
}
} catch (Exception e) {
log.info("出错了");
} finally {
countDownLatch.countDown();
}
}
});
}
try {
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}