Create a thread

1. Create normal objects that simply allocate a chunk of memory in the JVM heap

2. To create a thread, you need to call the API of the operating system kernel, and then the operating system needs to allocate a series of resources for the thread, which costs a lot

  • A thread is a heavyweight object and should avoid frequent creation and destruction in favor of thread pools

General pooled resources

// Assume that Java Thread pools are designed to pool resources in a general sense. Class ThreadPool {// Get free threadsacquireVoid release(Thread t) {}} Thread T1 = pool.acquire(); // Pass the Runnable object t1.execute (() -> {// specific business logic});Copy the code

Producer-consumer model

The design of thread pool in the industry generally adopts the producer-consumer mode, in which the user of thread pool is the producer and the thread pool itself is the consumer

Public class MyThreadPool {class WorkerThread extends Thread {@override public voidrun() {// loop the task and execute itwhile (true) { Runnable task = null; try { task = workQueue.take(); } catch (InterruptedException e) { } task.run(); Private BlockingQueue<Runnable> workQueue; Threads = new ArrayList<>(); public MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue) { this.workQueue = workQueue;for(int i = 0; i < poolSize; i++) { WorkerThread work = new WorkerThread(); work.start(); threads.add(work); }} // Submit the task public void execute(Runnablecommand) throws InterruptedException {
        workQueue.put(command); } public static void main(String[] args) throws InterruptedException {// Create BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2); // Create thread pool MyThreadPool pool = new MyThreadPool(10, workQueue); Pool.execute (() -> {system.out.println ()"hello"); }); }}Copy the code

Java thread pools

Ⅰ ThreadPoolExecutor.

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory ThreadFactory, RejectedExecutionHandler handler Public void allowCoreThreadTimeOut(Boolean value)Copy the code

1. CorePoolSize: the minimum number of threads held in the thread pool

2. MaximumPoolSize: specifies the maximum number of threads that can be created in the thread pool

3.keepAliveTime & unit

  • If a thread is idle with keepAliveTime & Unit and the thread pool is larger than corePoolSize, the idle thread is reclaimed

4. WorkQueue: indicates a workQueue

5. ThreadFactory: Customize how threads are created

6.handler

  • If all threads in the thread pool are busy and the work queue is full (a bounded queue), the thread pool will reject the submitted task
  • CallerRunsPolicy: The thread submitting the task executes the task itself
  • AbortPolicy: default refusal strategies, throw RejectedExecutionException
  • DiscardPolicy: Discards the task without throwing any exceptions
  • DiscardOldestPolicy: Discards the oldest task and adds the new task to the work queue

Ⅱ Executors.

1. Do not recommend using Executors because many of the default methods provided by Executors use the unbounded LinkedBlockingQueue

2. In the case of high load, unbounded queue is prone to OOM, and OOM will result in all requests cannot be processed

3. The use of bounded queues is therefore strongly recommended

ⅲ. Rejection strategy

1. Use bounded queues. When there are too many tasks, the thread pool triggers a rejection policy

2. The default thread pool refusal strategies will be thrown RejectedExecutionException, this is a runtime exception, development time is easy to ignore

3. If the thread pool processes important tasks, you can customize the rejection policy

ⅳ. Exception handling

1. Use ThreadPoolExecutor. The execute () method to submit tasks, if a task in the execution of a runtime exception

  • Causes the thread executing the task to terminate with no notification

2. Therefore, it is safest to catch all exceptions and handle them

Try {// business logic} catch (RuntimeException x) {// on demand} catch (Throwable x) {// on demand}Copy the code

Write in the last