多线程运行怎么分配线程数和每个线程读取的start和end
背景:最近项目中用到了多线程并发,需要将一批任务用多个线程来并发执行,
首先根据runNumPerThread,计算线程数,然后跟最大线程数取较小的值作为最终的线程数
然后根据最终的线程数计算出每个线程要运行的start和end
前n-1个线程都是运行runNumPerThread个请求,
最后一个线程运行total-(n-1)*runNumPerThread个请求,
int total=10000; //总的任务数 int maxThreadCount=5; //最大线程数 int runNumPerThread=200; //每个线程运行的任务数量的初始值 int threadCount = 0; //最终的线程数 if (total % runNumPerThread == 0) { threadCount =total / runNumPerThread > 0 ? total / runNumPerThread : 0; } else { threadCount = total / runNumPerThread > 0 ? total / runNumPerThread + 1 : 1; } threadCount=threadCount>maxThreadCount?maxThreadCount:threadCount; runNumPerThread=total/threadCount; for (int i = 0; i < threadCount; i++) { int start = i * runNumPerThread; int end = 0; if (i == threadCount - 1 && total % runNumPerThread != 0) { end = start + total-i*runNumPerThread - 1; } else { end = start + runNumPerThread - 1; } System.out.println("start="+start+",end="+end); }