Java thread pool-asynchronous task, java thread pool asynchronous

Source: Internet
Author: User

Java thread pool-asynchronous task, java thread pool asynchronous

1. simple and crude thread

The most primitive method: when we want to execute a task in parallel or asynchronously, We will directly start a thread, as shown below:

New Thread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub here put the method you want to execute}). start ();

 

However, there are many drawbacks such as the above or similar method that uses a new Thread every time, as shown below:

  • Poor performance of newly created objects in each new Thread;
  • There is a lack of unified management of threads, there is no limit to the creation of new threads, and competition between them may also occupy too much system resources, leading to crashes or OOM (Out of Memory );
  • More functions are lacking, such as scheduled execution, scheduled execution, and thread interruption.

Ii. Thread Pool

To solve these problems, the java. util. concurrent package was added after Jdk1.5. This package mainly introduces the use of threads and thread pools in java. It provides great help for us to handle thread issues during development.

1. Role

Depending on the system environment, you can automatically or manually set the number of threads to achieve the best running effect. This reduces the waste of system resources, resulting in low system congestion efficiency. Use the thread pool to control the number of threads and wait in queue for other threads. After a task is executed, the task starts from the top of the queue. If no process is waiting in the queue, this resource in the thread pool is waiting. When a new task needs to run, if there is a waiting working thread in the thread pool, it can start to run; otherwise, it enters the waiting queue.

2. Why thread pool?

  • Reuse existing threads to reduce the overhead of object creation and elimination, and improve performance.
  • It can effectively control the maximum number of concurrent threads, improve the usage of system resources, and avoid excessive resource competition and congestion.
  • Provides scheduled execution, scheduled execution, single thread, concurrency control, and other functions.
  • You can adjust the number of worker threads in the thread pool according to the system's capacity to prevent servers from getting tired due to excessive memory consumption (each thread requires about 1 MB of memory, the more threads open, the larger the memory consumed, and the machine crashes ).

3. Main classes

The top-level interface of the thread pool in Java is Executor, but in a strict sense, Executor is not a thread pool, but a tool for executing the thread. The real thread pool interface is ExecutorService.

ExecutorService

Real thread pool interface.

ScheduledExecutorService

It can be similar to Timer/TimerTask to solve the problem of repeated task execution.

ThreadPoolExecutor

ExecutorService default implementation.

ScheduledThreadPoolExecutor

Inherits the implementation of the ScheduledExecutorService interface of ThreadPoolExecutor and class implementation of periodic task scheduling.

It is complicated to configure a thread pool, especially when the thread pool principle is not clear, it is very likely that the thread pool configured is not optimal, therefore, some static factories are provided in the Executors class to generate some common thread pools.

1) newSingleThreadExecutor

Creates a single-threaded thread pool. This thread pool only has one thread working, which is equivalent to a single thread serial execution of all tasks. If this unique thread ends due to an exception, a new thread will replace it. This thread pool ensures that all tasks are executed in the order they are submitted.

2)NewFixedThreadPool

Create a fixed thread pool. Each time a task is submitted, a thread is created until the thread reaches the maximum size of the thread pool. The size of the thread pool remains unchanged once it reaches the maximum value. If a thread ends due to an execution exception, the thread pool will add a new thread.

3)NewCachedThreadPool

Create a cacheable thread pool. If the thread pool size exceeds the thread required for processing the task,

Then, some Idle threads (which do not execute tasks in 60 seconds) will be reclaimed. When the number of tasks increases, the thread pool can intelligently add new threads to process the tasks. This thread pool does not limit the thread pool size. The thread pool size depends entirely on the maximum thread size that can be created by the operating system (or JVM.

4)NewScheduledThreadPool

Creates an infinite thread pool. This thread pool supports regular and periodic task execution requirements.

Iii. Instances

1)NewCachedThreadPool
Create a cache thread pool. If the thread pool length exceeds the processing requirement, free threads can be recycled flexibly. If no thread pool can be recycled, a new thread is created. The sample code is as follows:

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService cachedThreadPool = Executors.newCachedThreadPool();  for (int i = 0; i < 10; i++) {   final int index = i;   try {    Thread.sleep(index * 1000);   } catch (InterruptedException e) {    e.printStackTrace();   }   cachedThreadPool.execute(new Runnable() {    public void run() {     System.out.println(index);    }   });  } }}

 

The thread pool is infinite. When the second task is executed and the first task is completed, the thread for executing the first task is reused instead of creating a new thread each time.

2) newFixedThreadPool
Create a fixed-length thread pool to control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue. The sample code is as follows:

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  for (int i = 0; i < 10; i++) {   final int index = i;   fixedThreadPool.execute(new Runnable() {    public void run() {     try {      System.out.println(index);      Thread.sleep(2000);     } catch (InterruptedException e) {      e.printStackTrace();     }    }   });  } }}

Because the thread pool size is 3 and each task outputs an index and sleep for 2 seconds, three numbers are printed every two seconds.
It is best to set the size of the fixed-length thread pool based on system resources. Such as Runtime. getRuntime (). availableProcessors ()

3) newScheduledThreadPool
Creates a fixed-length thread pool that supports scheduled and periodic task execution. Example code of delayed execution:

package test;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  scheduledThreadPool.schedule(new Runnable() {   public void run() {    System.out.println("delay 3 seconds");   }  }, 3, TimeUnit.SECONDS); }}

The execution is delayed by 3 seconds.

Periodically execute the following sample code:

package test;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  scheduledThreadPool.scheduleAtFixedRate(new Runnable() {   public void run() {    System.out.println("delay 1 seconds, and excute every 3 seconds");   }  }, 1, 3, TimeUnit.SECONDS); }}

It indicates that the task is executed every 3 seconds after a delay of 1 second.

4) newSingleThreadExecutor
Create a single-threaded thread pool. It only uses a unique worker thread to execute tasks and ensures that all tasks are executed in the specified order (FIFO, LIFO, priority. The sample code is as follows:

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  for (int i = 0; i < 10; i++) {   final int index = i;   singleThreadExecutor.execute(new Runnable() {    public void run() {     try {      System.out.println(index);      Thread.sleep(2000);     } catch (InterruptedException e) {      e.printStackTrace();     }    }   });  } }}

The results are output in sequence, which is equivalent to executing each task in sequence.

Note: The preceding execute () method can be replaced with the submit () method, and the execution result is the same.

Iv. Differences between submit () and execute ()

After JDK 5, there are two types of tasks: one is the class that implements the Runnable interface and the other is the class that implements the Callable interface. Both of them can be executed by ExecutorService. Their differences are:

  • Execute (Runnable x) has no returned value. The task can be executed, but it cannot be determined whether the task is successfully completed. -- Implement the Runnable interface
  • Submit (Runnable x) returns a future. You can use this future to determine whether the task is successfully completed. -- Implement the Callable Interface

 

Thank you!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.