JAVA single row diary -2020 / 1/21 thread pool

1. Overview of the thread pool ideas

  • Frequent elimination and create a thread takes time, repeated use of the same thread can improve efficiency

2. The concept of the thread pool

  • Thread pool: a collection of threads
LinkedList<Thread> threads = new LinkedList<>();

Add Thread:

LinkedList<Thread> threads = new LinkedList<>();
threads.add(new Thread("线程1"));
threads.add(new Thread("线程2"));
threads.add(new Thread("线程3"));
threads.add(new Thread("线程4"));

The calling thread:

Thread thread01 = threads.removeFirst();
Thread thread02 = threads.removeFirst();

After use, also back thread

threads.addLast(thread01);
threads.addLast(thread02);

After JDK1.5

  1. Use the thread pool factory class Executorsinside a static method of newFixedThreadPool()producing a specified number of thread pool
ExecutorService es = Executors.newFixedThreadPool(3); 生产3个线程,
  1. Creating a Runnableclass that implements the interface, rewrite run()method, set the thread task
public class ImpRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  1. Using the ExecutorServicemethod submit(), passing threaded tasks (implementation class), open thread execution run()method
es.submit(new ImpRunnable());
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo05 {
    public static void main(String[] args) {
        ExecutorService es= Executors.newFixedThreadPool(3);
        es.submit(new ImpRunnable());
        es.submit(new ImpRunnable());
        es.submit(new ImpRunnable());
        es.submit(new ImpRunnable());

    }
}

Here Insert Picture Description

  1. Using the ExecutorServicemethod of shutdown()destruction thread pool (not recommended)
es.shutdown();
Published 90 original articles · won praise 1 · views 2030

Guess you like

Origin blog.csdn.net/wangzilong1995/article/details/104064046