Java thread pool Analysis

Source: Internet
Author: User

Before Java 5.0, a task is started by calling the START () method of the thread class. The task is submitted and executed simultaneously, if you want to schedule the task execution or control the number of concurrent threads, you need to write additional code. 5.0 provides a new task execution architecture that allows you to easily schedule and control task execution, and create a thread pool similar to a database connection pool to execute tasks. This architecture mainly consists of three interfaces and their corresponding classes. These three interfaces are executor, executorservice, and scheduledexecutorservice. Let's use a graph to show their relationship:

Interfaces are displayed on the left and specific classes of interfaces are displayed on the right. Note that executor is not directly implemented.

 

ExecutorInterface:Is used to execute the runnable task. It defines only one method:

 

  • Execute (Runnable command): Executes a Ruannable task.

 

ExecutorServiceInterface:Executorservice inherits the executor method and provides the services for executing the callable task and suspending the task execution. The methods defined mainly include:

 

  • Submit (Task): Used to submit a Callable or Runnable task and return a Future object representing the task.
  • InvokeAll (Collection of tasks): A batch processing task set and a Future object set that represents these tasks.
  • Shutdown (): closes the service after the submitted task is completed and no longer accepts the new task.
  • ShutdownNow (): stops all ongoing tasks and closes the service.
  • IsTerminated (): test whether all tasks have been completed.
  • Isshutdown (): test whether the executorservice has been disabled

 

ScheduledExecutorServiceInterfaceBased on executorservice, scheduledexecutorservice provides the time-based task execution function. It provides the following methods:

 

  • Schedule (Task, initDelay): Schedule the submitted callable or runnable tasks to be executed after the time specified by initdelay.
  • Scheduleatfixedrate (): Schedule the submitted runnable tasks to be executed repeatedly at the specified interval.
  • Schedulewithfixeddelay (): Schedule the submitted runnable task to be executed again after each execution, waiting for the time specified by delay.

 

 

 

Important ExecutorsClass

 

Although the interfaces mentioned above have specific classes for implementation, we recommend that you use the tool class of executors in Java 5.0 to obtain specific objects of the executor interface. It is worth noting that executors is a class, it is not the plural form of executor. Executors provides the following static methods:

 

  • Callable (Runnable task): Converts a runnable task to a callable task.
  • Newsinglethreadexecutor: generates an executorservice object. This object has only one thread to execute the task. If there are more than one task, the task is executed sequentially.
  • Newcachedthreadpool (): generates an executorservice object with a thread pool. The size of the thread pool is adjusted as needed. The thread returns to the thread pool after the task is executed, used to execute the next task.
  • Newfixedthreadpool (Int poolSize): Generate an executorservice object with a poolsize thread pool. If the number of tasks is greater than the poolsize, the task will be executed sequentially in a queue.
  • Newsinglethreadscheduledexecutor: generates a scheduledexecutorservice object. The thread pool size of this object is 1. If there are more than one task, the task will be executed in sequence.
  • Newscheduledthreadpool (Int poolSize): Generate a scheduledexecutorservice object. The thread pool size of this object is poolsize. If the number of tasks is greater than poolsize, the task will be waiting for execution in a queue.

 

 

 

Example:

 

Executors is used to create a Thread pool.

 

 

 

Sometimes you need to build a bunch of threads to execute some small tasks. However, frequent Thread creation may be an overhead, because the Thread creation must interact with the job system, if you can create a Thread pool to manage these small threads and reuse them, the system performance will be improved.

You can use Executors to create a Thread pool. Executors has several static methods, which are listed as follows:

 

Method Description
NewCachedThreadPool Creates a Thread that can be cached. Each Thread can be set to idle for 60 seconds by default.

Newfixedthreadpool

Includes a fixed number of threads

Newsinglethreadexecutor

There is only one Thread, and each task assigned to it by sequential execution
NewScheduledThreadPool Schedulable Thread
Newsinglethreadscheduledexecutor Single Thread that can be scheduled

 

For a simple example, the following program uses the newFixedThreadPool method to create a Thread pool, which includes five reusable threads. You can specify a Runnable object for it, ten Runnable objects will be generated in the program. Because there are only five available threads in the Thread pool, the five Runnable created later must wait for Idle threads to be executed:

 

  • ExecutorDemo. java

 

Package onlyfun. caterpillar; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class ExecutorDemo {public static void main (String [] args) {ExecutorService service = Executors. newFixedThreadPool (5); for (int I = 0; I <10; I ++) {final int count = I; service. submit (new Runnable () {public void run () {System. out. println (count); try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace () ;}});} service. shutdown (); // close the Thread pool }}

 

The submit () method also accepts the objects implemented as Callable interfaces, and finally returns the Future object, which can obtain the returned results after Callable execution.

If you want to schedule jobs using Executors, for example, 30 seconds after a job is scheduled:

 

ScheduledExecutorService schedors = Executors. newSingleThreadScheduledExecutor ();
Schedable. schedule (new Runnable (){
Public void run (){
// Schedule jobs
}
},
30, timeunit. Seconds );

 

Or schedule a job to be executed after 5 seconds, and then run once every 30 seconds:

 

Scheduledexecutorservice schedors = executors. newsinglethreadscheduledexecutor ();
Final scheduledfuture future = schedure. scheduleatfixedrate (New runnable (){
Public void run (){
// Schedule jobs
System. out. println ("t ");
}
},
0, 5, TimeUnit. SECONDS );

// Cancel the future after 60 seconds.
Schedable. schedule (new Runnable (){
Public void run (){
Future. cancel (false );
}
}, 60, TimeUnit. SECONDS );
As shown above, to cancel a schedule task, call the cancel () method of ScheduledFuture.

 

 

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.