JAVA basics | Four thread pools provided by Executors

1. Thread and Executors

 To start a new thread, we often use the following methods:

        Thread thread =new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("new thread");
            }
        });

Through the new Thread() method, it will lead to many disadvantages, as follows:

  • Every time through the new Thread method, the performance is poor.
  • Threads lack unified management, which may create unlimited new threads, compete with each other, and may occupy too many system resources and cause downtime.
  • Lack of functions such as timed execution, periodic execution, and thread interruption.

The four thread pools provided by Executors effectively solve the above problems

2. Four thread pools provided by Executors

  • newCachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, it can flexibly recycle idle threads. If there is no reclamation, a new thread is created.
  • newFixedThreadPool creates a fixed-length thread pool, which can control the maximum number of concurrent threads, and the excess threads will wait in the queue.
  • newScheduledThreadPool creates a fixed-length thread pool that supports both scheduled and periodic task execution.
  • newSingleThreadExecutor creates a single-threaded thread pool that only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order.

newCachedThreadPool

        ExecutorService executorService1 = Executors.newCachedThreadPool();
        Future<String> future = executorService1.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return "newCachedThreadPool";
            }
        });
        try {
            System.out.println(future.get());
        } catch (Exception e) {
            e.printStackTrace ();
        }

newFixedThreadPool

        ExecutorService executorService2 = Executors.newFixedThreadPool(3); // Fixed length 3 threads 
        for ( int i = 0; i < 10; i++ ) {
            executorService2.execute(new Runnable() {//execute与submit的区别
                @Override
                public void run() {
                    try {
                        System.out.println( "Three threads with fixed length" );
                        TimeUnit.SECONDS.sleep( 3); // Note the difference from Thread.sleep(3000) 
                    } catch (InterruptedException e) {
                        System.out.println("InterruptedException");
                    } catch (Exception e) {
                        System.out.println("Exception");
                    }
                }
            });
        }

Every three seconds, print three pieces of data

五、newScheduledThreadPool

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);//定长三个线程
        scheduledThreadPool.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println( "Delayed output for three seconds" );
            }
        }, 3, TimeUnit.SECONDS);

Delayed output for three seconds

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);//定长三个线程
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println( "Delay for 1 second, then execute periodically every three seconds" );
            }
        },1, 3, TimeUnit.SECONDS);

Delay one second, then execute periodically

、 、 NewSingleThreadExecutor

        ExecutorService executorService4 = Executors.newSingleThreadExecutor();
         for ( int i = 1; i < 11; i++ ) {
             // All local variables accessed by inner classes must be modified with final
             // For ordinary local variables, when the method After the end, the local variable will also disappear.//But
             if the life cycle of the anonymous inner class does not end, the value of the local variable will always be accessible, and the inner class will expand the scope of the local variable, which will cause confusion 
            final  int index = i;
            executorService4.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread:" + index);
                }
            });
        }

Seven, other knowledge points

7.1, the difference between submit and execute

  • submit supports Callable, execute supports Runable
  • submit has a return value, execute has no return value
  • submit can catch exceptions (or because it supports Callable), execute cannot

7.2, the difference between shutdown and shutdownNow

  • shutdown() method allows execution of ongoing threads before terminating
  • The shutdownNow() method blocks new processes and attempts to stop currently executing threads, shutting down unused ExecutorServices to allow their resources to be reclaimed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324894721&siteId=291194637