Multi-threaded study notes (3) multi-threaded thread pool

introduction

When a business has a large amount of concurrency, multithreading must be used, and when running ordinary multithreaded programs, it will be accompanied by a large number of repeated thread creation and thread destruction. These unnecessary and repeated computing tasks will increase the program's The complexity does not conform to the principle orientation of computer programming. In order to improve the efficiency of computer use, the predecessors to the elders proposed to use the thread pool, which avoids the repeated creation and destruction of threads to a certain extent, which greatly improves The execution efficiency and robustness of the program.

Introduction and usage of thread pool

What is a thread pool?

  • As the name implies, the thread pool is a "pool" that holds threads, that is, a container that can hold multiple multi-threaded programs. The advantage of this is that it can avoid the overhead of repeatedly closing threads and opening threads during the execution of multi-threaded programs. To a great extent Reduce the time complexity of the program, and the price is to increase the program a little space complexity.

Principle of Thread Pool

  • The principle of the thread pool is very simple. First, create a thread pool. The thread pool contains multiple threads. When there are multiple task fragments to be executed in the system, the current task fragment can be matched with the threads in the thread pool. If the task is successful The task fragment can be executed by obtaining the thread object. The schematic diagram of this process is as follows:
    Insert picture description here
  • If the task execution is completed, the system will automatically return the thread resources. In the above figure, tasks 3 and 4 have not obtained thread resources and need to wait in line.
  • The thread pool is composed of collections, and common collections in Java include ArrayList, HashSet, LinkList, HashMap. According to the characteristics of these collections, the most suitable collection for thread pool containers is LinkList. The schematic diagram of the principle of LinkList implementation of thread pool is shown below.
    Insert picture description here

Thread pool case

After the jdk1.5 version, the jdk includes the thread pool class, which is unified under the java.util.concurrent package. If you want to use the thread pool, you can directly import the package. Similar to the previous notes, Xiao Yuan also uses the ticket purchase case in this note. The following is Xiao Yuan's case code.
Runnable interface implementation class:

public class MyRunnableImpl implements Runnable{
    private static int ticket =100;
    private  int ticket2 =500;
    private  static volatile boolean sellOutFlag=false;
    private   String name;
    public MyRunnableImpl() {

    }
    public MyRunnableImpl(String name) {
        this.name = name;
    }
    @Override
    public void run() {

        while (!sellOutFlag) {
            sellTicketStatic();
            //sellTicket();
        }
    }
    //锁对象是自己
    private synchronized void sellTicket() {
            if(ticket>0){
                //System.out.println(this.name+"正在卖出第:"+ticket+"张票");
                System.out.println(Thread.currentThread().getName()+"正在卖出第:"+ticket+"张票");
                //所以打印出来会连续减三
                ticket --;
                //System.out.println(name+"正在卖出第:"+ticket+"张票");
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                sellOutFlag = true;
            }
    }
    //锁对象是MyRunnableImpl类
    public  static synchronized void sellTicketStatic(){

            if(ticket>0){
                //System.out.println(this.name+"正在卖出第:"+ticket+"张票");
                //System.out.println(name+"正在卖出第:"+ticket+"张票");
                System.out.println(Thread.currentThread().getName()+"正在卖出第:"+ticket+"张票");
                ticket --;
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                sellOutFlag = true;
            }
    }
}

Test class

public class ThreadPoolDemoTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(new MyRunnableImpl("窗口一"));
        executorService.submit(new MyRunnableImpl("窗口二"));
        executorService.submit(new MyRunnableImpl("窗口三"));
        executorService.shutdown();
    }
}

Test Results
Insert picture description here
Insert picture description here

to sum up

In the above code, Xiaoyuan fixed the number of thread pools to 3, and 3 thread pools can also accommodate 3 threads to run, so the test result will have the condition that all three threads are buying tickets, and when we change the number of thread pools When it is fixed to 2, according to the principle, there should be only two threads selling tickets. As for the specific test. Xiao Yuan recommends that all students take the test in their spare time.

Guess you like

Origin blog.csdn.net/xueshanfeitian/article/details/106671652