Java Advanced----Main thread waiting for sub-threading various scenarios comparison

Source: Internet
Author: User

basic understanding of creating threads and managing thread pools
Refer to the original link: http://www.oschina.net/question/12_11255?sort=time

One, create a simple Java thread
In the Java language, one of the simplest threads is shown in the following code:

Java code
    1. Runnable Runnable = new Runnable () {
    2. public Void Run () {
    3. System.out.println ("Run");
    4. }
    5. }



This thread can be started by the following line of code:
New Thread (runnable). Start ();
This is a simple example, but if you have a lot of long-running tasks to execute at the same time, and you need to wait for all of these threads to execute, and you want a return value, it's a little bit difficult. But Java already has a solution for you, and that's executors, a simple class that lets you create thread pools and thread factories.

ii. executors creating a thread pool
A thread pool is represented by an instance of class Executorservice, through which you can submit a task and execute it in a scheduled executorservice. Here are some of the types of thread pools you can create through the executors class:

1.Single thread Executor: There is only one thread pool, so all committed tasks are executed sequentially, code:

Java code
    1. Executors.newsinglethreadexecutor ()


2.Cached thread pool: There are many threads in the thread pool that need to be executed at the same time, the old available thread will be re-executed by the new task, and if the thread is not executed within 60 seconds, it will be terminated and removed from the pool, code:

Java code
    1. Executors.newcachedthreadpool ()


3.Fixed thread pool: A thread pool that has a fixed number of threads, and if there is no task to execute, the threads will wait until the code:

Java code
    1. Executors.newfixedthreadpool ()


4.Scheduled thread pool: The thread pool that is used to dispatch the task that is about to be executed, code:

Java code
    1. Executors.newscheduledthreadpool ()


5.Single Thread scheduled Pool: Only one thread is used to schedule the execution of future tasks, code:

Java code
    1. Executors.newsinglethreadscheduledexecutor ()



third, the main thread waits for a child thread to end various ways
Once you have created a thread pool, you can submit the task to the pool in different ways, either by committing Runnable or callable to the thread pool, which returns a future instance representing the state of the task, and if you commit a Runnable, if the task is completed The future object returns NULL.

For example, you write the following callable:

Java code
    1. private final class stringtask extends callable<string>{  
    2.    public string call () {   
    3.       //long operations   
    4.    
    5.        return 
    6.    }  
    7. }  



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 thread pool end all the threads in the pool:

Pool.shutdown ();

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

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

The following example can also block the main thread from waiting for a child thread to complete, but that way, if the first thread is blocked for a long time, the other threads may have been executed, and many cases are not applicable

Java code
  1. Executorservice pool = Executors.newfixedthreadpool (4);
  2. List<future<string>> futures = new arraylist<future<string>> (10);
  3. for (int i = 0; i < i++) {
  4. Futures.add (Pool.submit (new Stringtask ()));
  5. }
  6. for (future<string> future:futures) {
  7. String result = Future.get ();
  8. //compute The result
  9. }
  10. Pool.shutdown ();



But this code is a little bit more complicated, and it's not enough. If the first task takes a very long time to execute, and then the other tasks are done before it ends, then when the front end is unable to get the execution results before the end of the first task, but don't worry, Java provides you with a solution--completionservice.

A completionservice is a service that simplifies the execution of a wait task, the class is Executorcompletionservice, and the class is based on Executorservice, so we can try the following code:


Java code
  1. Executorservice ThreadPool = Executors.newfixedthreadpool (4);
  2. Completionservice<string> pool = new executorcompletionservice<string> (ThreadPool);
  3. for (int i = 0; i < i++) {
  4. Pool.submit (new Stringtask ());
  5. }
  6. for (int i = 0; i < i++) {
  7. String result = Pool.take (). get ();
  8. //compute The result
  9. }
  10. Threadpool.shutdown ();



With this code, we can get the corresponding result in the order that execution ends, without having to maintain a collection of future objects.
This is all in this article, through Java to provide us with a variety of tools, can be easily multi-tasking programming, by using executors, Executorservice and completionservice tools such as, we can create complex parallel task execution algorithm , and you can easily change the number of threads.

http://825635381.iteye.com/blog/2184605

Java Advanced----Main thread waiting for sub-threading various scenarios comparison (RPM)

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.