1. 线程测试Demo
结论在注释中,建议自己跑一跑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolExecutorTest {
private static final int taskCount = 5;
public static void main(String[] args) throws InterruptedException { AtomicInteger integer = new AtomicInteger(); ThreadPoolExecutor executor = new ThreadPoolExecutor( 10, 20, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(30)); System.out.println("总任务数:" + taskCount); long start = System.currentTimeMillis(); for (int i = 0; i < taskCount; i++) { Thread thread = new Thread(() -> { try { Thread.sleep(500); System.out.println("已执行" + integer.addAndGet(1) + "个任务"); } catch (InterruptedException e) { e.printStackTrace(); } }); try { executor.execute(thread); } catch (Exception e) { System.out.println(e.getMessage()); } } long end = 0; while (executor.getCompletedTaskCount() < taskCount) { end = System.currentTimeMillis(); } System.out.println("任务总耗时:" + (end - start)); } }
|
2. 结论
每组执行时间就等于单个任务执行时间(demo 中为 500ms)
当任务数 <= 核心线程数时,线程池中工作线程数 = 任务数
当核心线程数 + 队列容量 < 任务数 <= 最大线程数 + 队列容量时,工作线程数 = 任务数 - 队列容量
因此demo中当 44 个线程的时候,工作线程数=44-30=14,
线程工作批次为 44 = 14+14+14+2 = 500+500+500+500 ≈ 2000ms。