1. API introduction

Executors. NewFixedThreadPool (10), create a fixed-size thread pool.

Two constructors

Executors.newFixedThreadPool(10);

Executors.newFixedThreadPool(10,Executors.defaultThreadFactory());

Number of threads coreSize

Number of threads, one ThreadFactory ThreadFactory

Thread pool logic

1. When the number of running threads in the thread pool is less than coreSize, new tasks are submitted and new threads are generated up to the maximum coreSize.

If a task is successfully added to the queue and needs to be retested, it is rejected because the thread pool has been closed or the thread pool has been terminated

 

Note: New tasks are created only when they are submitted. A thread pool of 10 threads was created, three tasks were submitted, and three threads were generated at run time.

 

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.submit(()-> System.out.println("1111111111111111111111"));
executorService.submit(()-> System.out.println("222222222222222222"));
executorService.submit(()-> System.out.println("3333333333333333333333"));
Copy the code

3. Digression: shift operation and bit operation

 

private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
private static int workerCountOf(int c)  { return c & CAPACITY; }
Copy the code

 

 

It seems that many programs do not.

The << right shift operation is equal to *2 to the n

&1 = 1 and 0 = 0

The << right shift operation completes 0 on the left. For example, if 1 moves 2 to the right, it becomes 100

Capacity-1 will change all the bits to 11,

Math.min(CAPACITY -1, c)

 

 

 

 

Welcome to reprint, I’m coriander, thank you. Welcome to join QQ group: 632603498, learn together