Java Concurrency: Executors and thread pool __java

Source: Internet
Author: User

This article translates from: Java concurrency–part 7:executors and thread pools

Let's start by getting to know Java concurrency programming from a primer.

This article describes how to start creating threads and managing the thread pool, in the Java language, a simplest thread is shown in the following code:

Runnable Runnable = new Runnable () {public
   void run () {
      System.out.println ("Run");
   }
}

You can start this thread by following a line of code:

New Thread (runnable). Start ();

This is a simpler example, but if you have a lot of long-running tasks to execute at the same time and need to wait for all of these threads to execute and get a return value, then this is a little tricky. But Java already has a solution for you, and that is executors, a simple class that allows you to create thread pools and threading factories.

A thread pool is represented by an instance of class Executorservice, through which you can submit a task and perform a dispatch executorservice. Here's a list of the types of thread pools you can create by using the Executors class: Single thread Executor: A thread pool of only one threads, so all the committed tasks are sequential execution, Code: Executors.newsinglethreadexecutor () Cached thread pool: There are many threads in the thread pools that need to be executed at the same time, and the old available threads will be executed by the new task, if the thread does not execute for more than 60 seconds, Then it will be terminated and removed from the pool, Code: Executors.newcachedthreadpool () fixed thread pool: thread pools that have a fixed number of threads, and if no task executes, the threads wait Code: Executors.newfixedthreadpool () scheduled thread pool: the thread pools that are used to dispatch upcoming tasks, Code: Executors.newscheduledthreadpool () Single thread scheduled Pool: Only one thread is used to schedule the execution of future tasks, code: Executors.newsinglethreadscheduledexecutor ()

Once you create a thread pool, you can commit the task in a different way to the pool, either by submitting Runnable or callable to the thread pool, which returns a Future instance representing the status of the task, if you submit a Runnable, if the task is completed The Future object returns NULL.

For example, you write the following callable:

Private Final class Stringtask extends callable<string>{public
   String call () {
      //long operations
 
      return "Run";
   }

If you want to use 4 threads to perform this task 10 times, then the code is as follows:

Executorservice pool = Executors.newfixedthreadpool (4);
 
for (int i = 0; i < i++) {
   pool.submit (new Stringtask ());
}

But you have to manually close the line pool end all the threads in the pool:

Pool.shutdown ();

If you do not, the JVM does not shut down the threads, and you can use the Shutdownnow () method to force off the thread pool, and the threads in execution are interrupted, and all tasks that have not yet been executed will no longer be executed.

But in this case, you can't get the execution status of the task, so we need to use the Future object:

Executorservice pool = Executors.newfixedthreadpool (4);
 
List<future<string>> futures = new arraylist<future<string>> (a);
 
for (int i = 0; i < i++) {
   futures.add pool.submit (New Stringtask ());
}
 
for (future<string> future:futures) {
   String result = Future.get ();
 
   Compute the result
}
 
Pool.shutdown ();

But this code is a little bit more complicated, and there is a shortage of places. If the first task takes a very long time to execute, and then the rest of the task is before it is over, then when the front line can't get the execution result before the first task ends, but don't worry, Java provides you with solution--completionservice.

A completionservice is a service that simplifies the execution of waiting tasks, the implementation of the class is Executorcompletionservice, the class is based on Executorservice, so we can try the following code:

Executorservice ThreadPool = Executors.newfixedthreadpool (4);
Completionservice<string> pool = new executorcompletionservice<string> (threadPool);
 
for (int i = 0; i < i++) {
   pool.submit (new Stringtask ());
}
 
for (int i = 0; i < i++) {String result
   = Pool.take (). get ();
 
   Compute the result
}
 
Threadpool.shutdown ();
With this code, we can get the corresponding result in the order that the execution ends, without having to maintain a collection of Future objects.

This is the whole of this article, through the various tools provided by Java, we can easily multitask programming, through the use of executors, Executorservice and completionservice tools, we can create complex parallel task execution algorithm , and you can easily change the number of threads.

Hopefully this essay will help you understand concurrent programming.


---


Executor   is a multitasking concurrency execution framework (Doug Lea) under Java5 that creates a thread pool similar to the database connection pool to perform tasks. This framework consists primarily of three interfaces and their corresponding concrete classes. Executor, Executorservice and scheduledexecutorservice .
   1, Executor interface: It is used to perform Runnable tasks, it defines only one method-execute (Runnable command), and performs ruannable type tasks.
   2, Executorservice interface: Inherits the Executor interface, provides services for performing callable tasks and aborting task execution.
   3, Scheduledexecutorservice interface: Inherits the Executorservice interface, provides the service that executes the task by the schedule.
   4, Executors class: For ease of use, it is recommended to use the Executors tool class to get the specific object of the Executor interface.

The executors class has several important ways to be concise here:
1. Callable (Runnable Task): Translating Runnable tasks into callable tasks
2, Newsinglethreadexecutor (): Produces a Executorservice object, this object only one thread can be used to perform tasks, if more than one task, the task will be executed sequentially.
3, Newcachedthreadpool (): Produce a Executorservice object, this object with a thread pool, the size of the thread pool will be adjusted as needed, the thread after the task to return to the thread pool for the next task to use.
4, Newfixedthreadpool (int poolsize): Produces a Executorservice object, this object with a size of the poolsize thread pool, if the number of tasks is greater than poolsize, the task will be placed in a queue In order to execute.
5, Newsinglethreadscheduledexecutor (): Produces a Scheduledexecutorservice object, this object's thread pool size is 1, if more than one task, the task will be executed sequentially.
6, Newscheduledthreadpool (int poolsize): Produces a Scheduledexecutorservice object, this object's thread pool size is poolsize, if the number of tasks is greater than poolsize, The task will wait for execution in a queue.

For instructions on the other classes of the executor framework, see the API documentation for Java 5


Here are a few simple examples, using a few of the main methods shown in example executors.
1. Task.java Task
2, Singlethreadexecutortest.java single-threaded execution program test
3, the Cachedthreadpooltest.java thread pool threads Execution Program test
4, the Fixedthreadpooltest.java thread pool threads execution program test (thread number fixed)
5. Daemonthreadfactory.java Daemon Thread Generation factory
6. Maxprioritythreadfactory.java high priority thread generation factory
7. Minprioritythreadfactory.java Small priority thread generation factory
8, Threadfactoryexecutortest.java in the custom thread generation factory test

    1, Task.java task Java code    package com.thread;     //Executable task     public class task implements runnable {       //   Interrupt Signal        volatile boolean stop = false;          //  How many times the task was executed        private int  runcount = 0;          //  task ID         private int taskId;          public task (int  taskid)  {           this.taskid = taskid ;           system.out.println ("Create Task-"  +  taskid);       }          //  PracticeRow Tasks        public void run ()  {               while  (!stop)  {                try {                    thread.sleep (;  )              } catch  (interruptedexception e)  {  

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.