线程池线程数选择及示例

在这里插入图片描述

cpu密集型

package PoolTime;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @BelongsProject: JAVAtest
 * @BelongsPackage: PoolTime
 * @Author: 
 * @CreateTime: 2023-02-26  19:30
 * @Description: TODO
 * @Version: 1.0
 */
public class CPUMainClass {
    public static void main(String[] args) {
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        System.out.println(availableProcessors);
        //实例化一个固定大小为10个线程的newFixedThreadPool线程池
        System.out.println("请输入线程池线程数,输入0则结束程序");
        Scanner scanner = new Scanner(System.in);
        int num =  scanner.nextInt();
        while(num!=0){
            long start = System.currentTimeMillis();
            final CountDownLatch latch = new CountDownLatch(50);
            ExecutorService excutorService = Executors.newFixedThreadPool(num);
//            List<Long> list1 = new ArrayList<>();
//            List<Long> list2 = new ArrayList<>();
            for (int i = 0; i <50 ; i++) {
//            excutorService.submit(new CPUTypeTest(list1,list2,latch));
                excutorService.submit(new CPUTypeTest(latch));

            }

            try{
                //使调用该方法的主线程处于等待状态,当倒数到0时主线程才执行。
                latch.await();
                long end = System.currentTimeMillis();
//                System.out.println(start);
//                System.out.println(end);
                System.out.println(num+"个线程花费时间:" + (end - start));
            } catch (InterruptedException e) {
                throw new RuntimeException("处理异常",e);
            }

            //关闭线程池
            excutorService.shutdown();
            System.out.println("请输入线程池线程数");
            num =  scanner.nextInt();
        }
        scanner.close();

//        excutorService.submit(new IOTypeTest(vector1,vector2));


}}

package PoolTime;

import java.util.concurrent.CountDownLatch;

/**
 * @BelongsProject: JAVAtest
 * @BelongsPackage: PoolTime
 * @Author:
 * @CreateTime: 2023-02-26  19:25
 * @Description: TODO
 * @Version: 1.0
 */
public class CPUTypeTest implements Runnable {

//
//    // 整体执行时间,包括在队列中等待的时间
//    List<Long> wholeTimeList;
//    // 真正执行时间
//    List<Long> runTimeList;


    private long initStartTime = 0;
    CountDownLatch latch;

    /**
     * 构造函数
     * @param runTimeList
     * @param wholeTimeList
     */
    public CPUTypeTest(CountDownLatch latch) {
        initStartTime = System.currentTimeMillis();
//        this.runTimeList = runTimeList;
//        this.wholeTimeList = wholeTimeList;
        this.latch=latch;
    }


    /**
     * 判断素数
     * @param number
     * @return
     */
    public boolean isPrime(final int number) {
        if (number <= 1)
            return false;
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0)
                return false;
        }
        return true;
    }


    /**
     * 計算素数
     * @param
     * @return
     */
    public int countPrimes(final int lower, final int upper) {
        int total = 0;
        for (int i = lower; i <= upper; i++) {
            if (isPrime(i))
                total++;
        }
        return total;
    }


    public void run() {
        long start = System.currentTimeMillis();
        countPrimes(1, 1000000);
        long end = System.currentTimeMillis();
        this.latch.countDown();
//        System.out.println("计数器"+this.latch);
//        long wholeTime = end - initStartTime;
//        long runTime = end - start;
//        wholeTimeList.add(wholeTime);
//        runTimeList.add(runTime);
//        System.out.println(" 单个线程花费时间:" + (end - start));
    }
}

IO密集型

package PoolTime.origin;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @BelongsProject: JAVAtest
 * @BelongsPackage: PoolTime.origin
 * @Author: 
 * @CreateTime: 2023-02-27  07:56
 * @Description: TODO
 * @Version: 1.0
 */
public class newThread {

    public static void test(){
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        System.out.println(availableProcessors);
        //实例化一个固定大小为10个线程的newFixedThreadPool线程池
        System.out.println("请输入线程池线程数,输入0则结束程序");
        Scanner scanner = new Scanner(System.in);
        int num =  scanner.nextInt();
        while(num!=0){
            long startTime=System.currentTimeMillis();
            //获取开始时间
        //实例化一个固定大小为10个线程的newFixedThreadPool线程池
        ExecutorService excutorService = Executors.newFixedThreadPool(num);
        final CountDownLatch latch = new CountDownLatch(150);
        
        for (int i = 0; i <150; i++) {
            int j = 1;
            System.out.println(i == j);
            //线程提交任务
            excutorService.submit(new CalaulationStudentsData(i,latch));

        }
        try{
            //使调用该方法的主线程处于等待状态,当倒数到0时主线程才执行。
            latch.await();
            long endTime=System.currentTimeMillis(); //获取结束时
            System.out.println(num+"程序运行时间: "+(endTime-startTime)+"ms");
        } catch (InterruptedException e) {
            throw new RuntimeException("学生进入学校多线程处理异常",e);
        }

            //关闭线程池
            excutorService.shutdown();
            System.out.println("请输入线程池线程数");
            num =  scanner.nextInt();
        }
        scanner.close();
    }

    public static void main(String[] args) {
        test();
    }
}
package PoolTime.origin;

import java.io.*;
import java.util.concurrent.CountDownLatch;

/**
 * @BelongsProject: JAVAtest
 * @BelongsPackage: PoolTime.origin
 * @Author: GuoYuan.Zhao
 * @CreateTime: 2023-02-27  07:55
 * @Description: TODO
 * @Version: 1.0
 */
public class CalaulationStudentsData implements Runnable {
    //学生数量
    int studentNumber;
    //锁存器
    CountDownLatch latch;

    /**
     * @Author:
     * @Description:
     * @CreateTime:  2022/12/30 9:38
     * @param: [studentNumber, latch]
     * @return:
     **/
    public  CalaulationStudentsData(int studentNumber, CountDownLatch latch){
        this.studentNumber=studentNumber;
        this.latch=latch;
    }
    /**
     * @Author:Guoyuan.Zhao
     * @Description:执行线程,这个是从接口实现的方法,线程去干什么
     * @CreateTime:  2022/12/30 9:39
     * @param: []
     * @return: void
     **/
    @Override
    public void run() {
        try {
            //计算学生学习数据的方法
            this.CalculationStudentData();
            //计数器减
            latch.countDown();
        }catch (Exception e){
            throw new RuntimeException("学生进入学校执行数据异常"+e);
        }
    }
    /**
     * @Author:Guoyuan.Zhao
     * @Description:计算学生数据的方法
     * @CreateTime:  2022/12/30 9:40
     * @param: []
     * @return: void
     **/
    private void CalculationStudentData() throws InterruptedException, IOException {
		//这里使用线程休眠的方式进行统计,因为频繁的io操作不会占用cpu资源,如有疑问,请参考下面链接
		
        Thread.sleep(100);

    }}

磁盘IO-为什么说IO密集型很少消耗CPU资源?

执行效果对比:
在这里插入图片描述

2*8 = 16
8+1 = 9

最终实验效果成功

线程池类型介绍

选择线程池的类型和确定线程池的线程数需要根据你的应用需求和场景来进行考虑。线程池是用来管理和调度线程的重要工具,不同的应用场景可能需要不同类型的线程池和不同数量的线程。下面是一些指导原则,可以帮助你选择适合的线程池类型和线程数量:

选择线程池类型:

FixedThreadPool(固定线程数的线程池): 如果你的应用场景需要一定数量的线程来处理任务,而且任务数量相对稳定,可以选择这种线程池。线程数是固定的,当有新任务提交时,如果所有线程都在忙碌,任务会被放入等待队列。

CachedThreadPool(缓存线程池): 如果你的应用需要根据任务的数量动态地调整线程数,适合使用这种线程池。线程数会根据任务负载自动扩展和收缩,适用于任务数量波动较大的场景。

SingleThreadExecutor(单线程线程池): 如果你需要保证任务按照顺序执行,并且只有一个线程在工作,可以选择这种线程池。适用于需要顺序处理的任务,如日志记录。

ScheduledThreadPool(定时任务线程池): 如果你需要执行定时任务或者延迟任务,可以选择这种线程池。它可以按照一定的调度计划来执行任务。

确定线程池的线程数:

任务的性质: 如果任务是计算密集型(CPU-bound),则线程数可以根据CPU核心数进行设置。如果是I/O密集型(I/O-bound),则可能需要更多的线程来避免阻塞。

系统资源: 考虑系统的可用内存和CPU资源。设置过多的线程可能会消耗过多的内存和CPU资源,影响整体性能。

任务响应时间: 如果你需要快速响应任务,可以适当增加线程数,但要注意不要过多,以免过度竞争CPU资源。

任务的平均执行时间: 如果任务执行时间很短,可以适当增加线程数,以充分利用CPU。但如果任务执行时间较长,过多的线程可能会导致线程切换开销增加,降低性能。

资源限制: 某些环境可能会有资源限制,如云服务器的实例类型。在这种情况下,你需要根据实例的资源限制来设置线程数。

总的来说,选择线程池类型和确定线程数需要综合考虑应用的性质、需求、系统资源等因素。一开始可以根据经验和基准测试来选择适合的线程池参数,然后根据实际情况进行调整和优化。

当设计线程池的线程数时,还有一些要考虑的因素:

并发性能测试: 在选择线程数之前,进行一些并发性能测试,以确定系统在不同线程数下的性能表现。这可以帮助你找到一个合适的线程数范围。

任务类型: 不同类型的任务对线程数的需求可能不同。比如,I/O密集型任务可能需要更多的线程,而计算密集型任务可能需要更少的线程。

线程等待时间: 考虑任务在线程池中的平均等待时间。如果等待时间较长,可以适当增加线程数,以提高任务响应速度。

任务优先级: 如果线程池中的任务有不同的优先级,需要根据优先级来调整线程数。高优先级的任务可能需要更多的线程资源。

资源竞争: 过多的线程可能会导致资源竞争和线程切换开销增加,降低性能。在调整线程数时,要注意避免过多的竞争。

内存使用: 每个线程都会占用一定的内存。要确保线程数不会导致过多的内存消耗,以免出现内存不足的情况。

监控和调整: 在线程池运行期间,定期监控线程池的性能和资源使用情况。根据监控结果,随时调整线程数以优化性能。

异步和并行: 考虑任务的异步执行和并行执行需求。异步任务可能需要较少的线程,而并行任务可能需要更多的线程。

预留资源: 要预留一定的线程数用于系统中的其他任务或操作,以避免线程池占用过多资源。

总之,选择线程池的线程数是一个需要综合考虑多方面因素的过程。初步的线程数选择可以通过测试和经验得出,但随着应用的发展和变化,需要不断地监控和优化线程池的性能和线程数设置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Circ.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值