Basic usage of multithreading and thread pool in java

  • 2021-11-13 07:20:56
  • OfStack

Directory preface inherits Thread Four common thread pools for implementing Runnale interface Callable thread pool. Summarize

Preface

In java, if a new thread is created for each request that arrives, the overhead is considerable. In actual use, the time and system resources consumed by the server in creating and destroying threads are quite large, and may even be much more than the time and resources consumed in processing actual user requests. In addition to the overhead of creating and destroying threads, active threads also consume system resources. If too many threads are created in one jvm, the system may run out of system resources due to excessive memory consumption or "over-switching". To prevent resource shortages, server applications need to take measures to limit the number of requests processed at any given time and minimize the number of threads created and destroyed, especially threads that consume more resources, so as to make the best use of them
Using existing objects to serve is the reason why the technology of "pooling resources" came into being.

Thread pool is mainly used to solve the problem of thread life cycle overhead and insufficient resources. By reusing threads over multiple tasks, the overhead of thread creation is spread over multiple tasks, and the delay of thread creation is eliminated because the thread already exists when the request arrives. In this way, the request can be serviced immediately, and the application can respond faster. In addition, by properly adjusting the number of threads in the thread, the situation of insufficient resources can be prevented.

Multithreading greatly improves the efficiency of program running, and we often open a thread to perform some time-consuming tasks in the development process. There are 4 ways to open a thread, which I will explain in detail in the following article.

Inheriting Thread

Inheriting Thread to perform tasks can indeed open 1 thread to perform tasks. If you often open 1 thread, it will also lead to waste of system resources.


public static class Mythread extends Thread{
        @Override
        public void run() {
            System.out.println(" Current thread "+Thread.currentThread().getId());
            int i = 10/2;
            System.out.println(" Running result "+i);
        }
    }
// The calling thread. 
public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**thread Implementation mode */
        Mythread mythread = new Mythread();
        mythread.start();// Startup thread 
        System.out.println("main--end");
}

Implement Runnale interface


public static class MyRunable implements Runnable {

    @Override
    public void run() {
        System.out.println(" Current thread "+Thread.currentThread().getId());
        int i = 10/2;
        System.out.println(" Running result "+i);

    }
}

Call.


/**
 * runable Startup mode of 
 */

MyRunable runable = new MyRunable();
new Thread(runable).start();
System.out.println("main--end");

Callable


/**
 * Callable You can allow return values 
 */

public static class Callale01 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(" Current thread "+Thread.currentThread().getId());
        int i = 10/2;
        System.out.println(" Running result "+i);
        return i;
    }
}

Call. Here you need to build futureTask with callable


/**
 * callale Startup mode of 
 */
FutureTask<Integer> futureTask =new FutureTask<>(new Callale01());
// Get the returned result. 
Integer i = futureTask.get();
new Thread(futureTask).start();
System.out.println(" The result returned is: "+i);

Thread pool

Thread pool is our java development, often used to open a multi-threaded way, thread pool, to manage their own threads. System resources can be saved. Usually, we will write the following 1 configuration in 1 configuration class


/**
 * 7 Large parameter 
 * corePoolSize :  1. Number of core threads [1 Direct existence ]:  After the thread pool is created. The number of threads that are ready. 
 * maxinumPoolSize: 2  Maximum number of threads 
 * keepaliveTime:  Survival time. Maximum wait time for idle threads. 
 * unit   Unit of waiting time 
 * blockingQueue  Blocking the queue. If many tasks will be placed in the queue, as long as the thread is idle, it will go to the queue to get it. 
 * threadFactory : The factory of threads. 
 * RejectExecutionHandler : If the queue is full. According to the strategy we specified. Refuse to perform the task. 
 *
 */
 ThreadPoolExecutor executor = new ThreadPoolExecutor(5,100,10,TimeUnit.SECONDS,
          new LinkedBlockingQueue<>(100),
                                                    Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

Four common thread pools.

1 newCachedThreadPool()

Create a cacheable thread pool. If the length of the thread pool exceeds the processing needs, it can flexibly recycle idle threads. If there is no recycling. A new thread is created.


Executors.newCachedThreadPool();

2.newFixedThreadPool(6)

Creates a fixed-size thread pool.

3 newScheduledThreadPool()

Thread pool of timed tasks.

4.newSingleThreadExecutor()


Executors.newSingleThreadExecutor();

Summarize


Related articles: