spring ThreadPoolTaskExecutor 实现线程阻塞

时间:2021-05-13 18:07:06

需求:我们知道java的thread类有join发法可让主线程阻塞直到子线程执行完毕,那么如何ThreadPoolTaskExecutor是否有功能呢?

我第一想法是ThreadPoolTaskExecutor是否有对应功能接口,找了下没找到,如果有技术大大知道的欢迎补充

既然没有那就自己实现一个,
有CountDownLatch可用,一个倒数计算器,只需在子线程每次只需完成后将计算器减一,CountDownLatch就可以阻塞当前线程,直到倒数计数器倒数到0 。
线程类

import java.util.List;
import java.util.concurrent.CountDownLatch;


public class TreadCase implements Runnable {

private List<Integer> returnIds;
private CountDownLatch countDownLatch;

public TreadCase(List<Integer> returnIds, CountDownLatch countDownLatch) {
this.returnIds = returnIds;
this.countDownLatch = countDownLatch;
}

public void run() {
for (Integer returnId :returnIds) {
System.out.println("富友代扣线程类启动 id="+returnId);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("富友代扣线程类关闭 ");
}
countDownLatch.countDown();
System.out.println("countDownLatch="+countDownLatch.getCount());
}


}

测试类

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

public class TestCase {

private static ThreadPoolTaskExecutor threadPoolTest = new ThreadPoolTaskExecutor();

public static void main(String[] args) {
threadPoolTest.initialize();
List<List<Integer>> idList = new ArrayList<List<Integer>>();
idList.add(new ArrayList<Integer>(Arrays.asList(1,2,3)));
idList.add(new ArrayList<Integer>(Arrays.asList(4,5)));
// 创建一个初始值为2的倒数计数器
CountDownLatch countDownLatch = new CountDownLatch(idList.size());

System.out.println("自动扣款多线开启" + new Date());
for (List<Integer> idListSub : idList) {
if (CollectionUtils.isEmpty(idListSub)) continue;
TreadCase thread = new TreadCase(idListSub, countDownLatch);
threadPoolTest.execute(thread);
}

// 阻塞当前线程,直到倒数计数器倒数到0
try {
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("自动扣款多线程结束" + new Date());
// threadPool.destroy();
}
}