线程池的使用案例

本文介绍了如何使用Java线程池解决接口调用时的效率问题。通过创建ThreadPoolExecutor,实现了两个并发执行的任务,分别通过submit和execute方法提交。线程池能够有效管理资源,避免串行执行导致的响应延迟,尤其适用于无需返回结果的场景以及多定时任务的并行处理。同时,文章提到了submit和execute的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程池可以解决以下场景:

1.当一个接口中,需要调用很多接口,而且互相独立时,如果串行执行,会使得接口响应缓慢(如果需要返回结果使用submit)。

2.当一个接口,调用其它接口且用时长不需要返回结果(可以使用excute)。

3.多个定时任务也可以使用线程池,因为@Scheduled是顺序执行,所以可以使用excute并行执行。

package com.chingchou.test.test;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Date 2021/11/16 9:21
 * @Created by jingzhou16
 * excute和submit的区别:https://www.cnblogs.com/liuchuanfeng/p/6956014.html
 */
public class TEST_THREAD {

    public static int value = 0;

    public static void main(String[] args) throws InterruptedException {

        ThreadPoolExecutor texecutor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

        texecutor.submit(new Runnable() {
            @Override
            public void run() {
                while(value<50){
                    synchronized ("suo"){
                        value = ++value;
                        System.out.println("线程一:"+value);
                    }
                }
            }
        });
        texecutor.submit(new Runnable() {
            @Override
            public void run() {
                while(value<50){
                    synchronized ("suo"){
                        value = ++value;
                        System.out.println("线程二:"+value);
                    }
                }
            }
        });
        texecutor.shutdown();
        while(true){
            if(texecutor.isTerminated()){
                System.out.println("所有的子线程都结束了!");
                break;
            }
            Thread.sleep(1000);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值