Java multi-threaded entry (four) - thread pool

Foreword

In the introductory Java multithreading (a) - alternate numbers printed on the screen, the letters we've created task class and put it into execution thread.

This approach to a single task is very convenient, but you must create a thread for each task, so for a number of tasks, this approach is not good.

Each task to create a new thread is likely to limit the flow and cause performance degradation.

Thread Pool

Thread pool is an ideal way to manage the number of concurrent tasks. In the thread pool, if one thread to complete the task, it can be re-used and to perform other tasks.

If all threads in the pool are not punishable idle state, but there are other tasks waiting to be executed, then the system will re-create a new thread to replace it. If at this time there is a thread for some reason interrupted, then the system will re-create a new thread to replace it.

If the thread pool are not used within 60 seconds, then the thread will terminate.

Use the thread pool

package P1;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.lang.Thread.sleep;

public class thread1 {


    public static void main(String[] args){
       //创建一个最大容量为3的线程池
        ExecutorService executor= Executors.newFixedThreadPool(3);
        //提交任务给线程池
        executor.execute(new PrintChar('a',100));
        executor.execute(new PrintChar('b',100));
        executor.execute(new PrintNum(100));

        //关闭线程池
        executor.shutdown();
    }
}
class PrintChar implements Runnable{

    private char charToPrint;//需要打印的字母
    private  int times;//需要打印的次数

    public PrintChar() {

    }

    public PrintChar(char charToPrint, int times) {
        this.charToPrint = charToPrint;
        this.times = times;
    }

    @Override
    public void run() {
        for (int i = 0; i <= times; i++) {
            System.out.println(charToPrint);
        }
    }
}

class PrintNum implements Runnable{
    private int lastNum;

    public PrintNum(int lastNum) {
        this.lastNum = lastNum;
    }

    @Override
    public void run() {
            for (int i = 1; i < lastNum; i++) {
                System.out.println(" " + i);
    }
}

Thinking

We create a maximum number of threads in the thread pool is 3 actuators in this program, we create a good task to add into the thread pool. Execution will create three three tasks concurrently executing threads

If the code that creates the thread pool instead

 ExecutorService executor= Executors.newCachedThreadPool();

So each thread pool will wait for the task to create a new thread, so that all tasks are executed concurrently.

After all tasks are executed, the thread pool will be closed.

Published 100 original articles · won praise 25 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43576028/article/details/102491644