1. Use of the simplest thread

  new Thread() {
            @Override
            public void run() {// business logic}}.start();Copy the code

But there are a lot of problems:

First, frequent object creation and destruction is a performance consuming affair;

2. If a large number of users occupy too many resources, our service may break down due to insufficient resources;

In summary, in actual development, this operation is not desirable.

2. Advantages and functions of thread pools

  1. Improve system performance and usage and reduce object creation and destruction.

  2. Can control the number of threads, effectively improve the use of server resources, to avoid the occurrence of downtime due to insufficient resources and other problems.

3. Four ways to use thread pools

3.1 newCachedThreadPool

If the number of threads in the thread pool is too large, it can effectively reclaim the excess threads, if the number of threads is insufficient, it can create new threads, the number of threads in the thread pool is unlimited

Disadvantages: When the service processing time is too long, threads are automatically created to execute other codes, which is uncontrollable.

  ExecutorService executor = Executors.newCachedThreadPool();

        for (int i = 0; i < 5; i++) {

            final int index = i;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ""+ index); }}); }Copy the code

3.2 newFixedThreadPool

You can automatically control the number of threads in the thread pool to avoid unnecessary performance costs.

ExecutorService executor = Executors.newFixedThreadPool(5); // Set the maximum capacity of the thread poolfor (int i = 0; i < 10; i++) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            final int index = i;

            executor.execute(() -> {
                try {
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "" + index);
            });
        }
        executor.shutdown();
Copy the code

3.3 newScheduledThreadPool

  1. This thread pool supports timed and periodic task execution.
  2. If the service execution time ends but the interval set by the thread pool has not reached, the service will not continue but wait.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); / / initialize the number of threads in thread pool executor. ScheduleAtFixedRate (newRunnable() {
            @Override
            public void run() {
                long start = new Date().getTime();
                System.out.println("ScheduleAtFixedRate Start time :"+ DateFormat.getTimeInstance().format(new Date())); try { Thread.sleep(1000); Catch (InterruptedException e) {e.printStackTrace(); } long end = new Date().getTime(); System.out.println("ScheduleAtFixedRate Execution time =" + (end - start) / 1000 + "m");
                System.out.println("ScheduleAtFixedRate Execution completion time:" + DateFormat.getTimeInstance().format(new Date()));
                System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ="); } }, 1, 5, TimeUnit.SECONDS); //1 delay how long to start; 2 Time IntervalCopy the code

3.4 newSingleThreadExecutor

A single thread pool, executed by a single thread from start to finish.

 ExecutorService executor = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 5; i++) {
            final int index = i;
            executor.execute(() -> {
                try {
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "" + index);
            });
        }
        executor.shutdown();
Copy the code