Spring ThreadPoolTaskExecutor 结合CountDownLatch 实现线程阻塞

Spring ThreadPoolTaskExecutor 结合CountDownLatch 实现线程阻塞

  • 业务场景,大家可能都会遇到,在遍历一个list的时候,需要对list中的每个对象,做一些复杂又耗时的操作,比如取出对象的uid,远程调用一次userservice的getUserByUid方法,这属于IO操作了,可怕的是遍历到每个对象时,都得执行一次这种RPC的IO操作(甚至不止一次,因为可能还有别的接口需要去调)还有复杂的业务逻辑需要cpu去计算。

  • java的thread类有join发法可让主线程阻塞直到子线程执行完毕,那么如何ThreadPoolTaskExecutor是否有功能呢。

  • 例子地址 https://github.com/csy512889371/learndemo/tree/master/ctoedu-ThreadPool-TaskExecutor

更多干货



spring.xml

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 核心线程数 -->
        <property name="corePoolSize" value="5"/>
        <!-- 最大线程数 -->
        <property name="maxPoolSize" value="10"/>
        <!-- 队列最大长度 >=mainExecutor.maxSize -->
        <property name="queueCapacity" value="25"/>
        <!-- 线程池维护线程所允许的空闲时间 -->
        <property name="keepAliveSeconds" value="3000"/>
        <!-- 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.  -->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
        </property>
    </bean>

ThreadRunnable

@Component
public class ThreadRunnable {

    @Autowired
    private TaskExecutor taskExecutor;

    public void executeThread(String result, CountDownLatch latch) {
        this.taskExecutor.execute(new TaskThread(result, latch));
    }

    private class TaskThread implements Runnable {
        private CountDownLatch latch;
        java.text.SimpleDateFormat dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private String result;

        private TaskThread(String result, CountDownLatch latch) {
            super();
            this.result = result;
            this.latch = latch;
        }

        public void run() {
            try {
                for (int i = 0; i < 10000; i++) {
                    // dateTimeFormat.format(new Date());
                }
                System.out.println("现在的时间为:" + dateTimeFormat.format(new Date()) + "    " + result);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (this.latch != null) {
                    latch.countDown();
                }
            }
        }
    }
}

ThreadRunnableTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring.xml")
public class ThreadRunnableTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    ThreadRunnable threadRunnable;

    @Test
    public void test() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);
        for (int i = 0; i < 11; i++) {
            threadRunnable.executeThread("架构师成长之路", latch);
        }
        latch.await();
        System.out.println("执行完毕了吗!");
    }
}
CountDownLatch是Java中的一个并发类,用于实现线程的阻塞和同步操作。它通过一个计数器来完成,计数器的初始值可以设定为任意整数,每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器的值变为0时,所有等待中的线程将被释放。 当一个或多个线程需要等待其他线程执行完特定任务后再继续执行时,可以使用CountDownLatch实现线程的阻塞。例如,如果有5个线程都需要等待其他线程完成某个任务后才能继续执行,可以创建一个初始值为5的CountDownLatch对象,然后在每个线程执行完任务后调用countDown()方法来减少计数器的值。当计数器的值变为0时,所有等待中的线程将被释放。 下面是一个简单的示例代码: ```java import java.util.concurrent.CountDownLatch; public class CountdownLatchExample { public static void main(String[] args) throws InterruptedException { int threadCount = 5; CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(() -> { // 执行任务 System.out.println("Thread started"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread finished"); // 减少计数器的值 latch.countDown(); }); thread.start(); } // 等待所有线程执行完毕 latch.await(); System.out.println("All threads finished"); } } ``` 在上述示例中,创建了5个线程,并且每个线程在执行完任务后调用了countDown()方法来减少计数器的值。主线程调用latch.await()方法来等待所有线程执行完毕。当所有线程都完成任务时,计数器的值为0,主线程将继续执行输出"All threads finished"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值