Understanding Java Executorservice Using _java in multiple threads

Source: Internet
Author: User

The Java.util.concurrent package provides classes on multithreaded operations, often using more executorservice and their implementation classes (such as Threadpoolexecutor), Executor,executors, Future,callable, etc.

1. Executorservice (inherited from Executor) interface: Provides some asynchronous multithreading methods, such as execute (), submit (), Shutdown (), Shutdownnow (), etc.

2. Executor interface: Execute the submitted task (thread), only one method execute (Runnable a)

2. Executors class: Provides some factory methods and some public methods to operate executor and threadfactory, such as newxxx (), xxxthreadfactory (), etc.

3. Futrue interface: Represents the results of thread execution, provides methods for getting thread execution results and canceling threads, such as Get (), cancle (), etc.

4. Callable Interface: JDK1.5 provides a return value for the thread to perform a new interface

Make a simple record of the understanding of Executorservice and future

Code:

public class Main {private static int count = 0;

    public static void Main (string[] args) {list<future> resultlist = new linkedlist<> ();  /** * Executors.newcachedthreadpool () creates a thread cache pool that, if 60s threads are not in use, stops the thread and removes the * Executors.newscheduledthreadpool from the cache pool () Creates a fixed-capacity thread pool in which the threads Execute * executors.newfixedthreadpool () with a fixed capacity of the threads cache pool * Executors.newsinglethreadexecuto
    R () capacity for one thread cache pool, there will only be one thread/executorservice Executorservice = Executors.newcachedthreadpool ();
        for (int i=0; i<10; i++) {Future Future = executorservice.submit (new callable<string> () {@Override
            Public String call () {try {System.out.println () Thread.CurrentThread (). GetName ());
          Thread.Sleep (5000);
          catch (Interruptedexception e) {e.printstacktrace ();
          int count = Main.count; System.out.println (Thread.CurrentThread (). GetName () + ". Start Main count: ... "+ count);
          Main.count = ++count; System.out.println (Thread.CurrentThread (). GetName () + ".
          End Main Count: ... "+ main.count);
        Return Thread.CurrentThread (). GetName ();
      }
      });
    Resultlist.add (future);
    } executorservice.shutdown (); for (Future future:resultlist) {try {System.out.println (Future.get () + "...).
      Is over ... ");
      catch (Interruptedexception e) {e.printstacktrace ();
      catch (Executionexception e) {e.printstacktrace ();
  } System.out.println ("Main thread end ...");
 }
}

Output:

Pool-1-thread-1 pool-1-thread-2 pool-1-thread-3 pool-1-thread-4 pool-1-thread-5 pool-1-thread-6 Pool-1-thread-8 pool-1-thread-9 pool-1-thread-10 pool-1-thread-1. Start Main count: ... 0 pool-1-thread-2. Start Main count: ... 0 pool-1-thread-3. Start Main count: ... 1 pool-1-thread-2. End Main Count: ... 1 pool-1-thread-1. End Main Count: ... 1 pool-1-thread-3. End Main Count: ... 2 pool-1-thread-1. Is over ... pool-1-thread-2 ... Is over ... pool-1-thread-4 ... Start Main count: ... 2 pool-1-thread-3. Is over ... pool-1-thread-4 ... End Main Count: ... 3 pool-1-thread-4. Is over ... pool-1-thread-5 ... Start Main count: ... 3 pool-1-thread-5. End Main Count: ... 4 pool-1-thread-5. Is over ... pool-1-thread-6 ... Start Main count: ... 4 pool-1-thread-6. End Main Count: ... 5 pool-1-thread-6. Is over ... pool-1-thread-7 ... Start Main count: ... 5 pool-1-thread-7. End Main Count: ... 6 pool-1-thread-7. Is over ... pool-1-thread-8 ... Start Main count: ... 6 pool-1-thread-8. End Main Count: ... 7 pool-1-thread-8. Is over ... pool-1-thread-9.. Start Main count: ... 7 pool-1-thread-9. End Main Count: ... 8 pool-1-thread-9. Is over ... pool-1-thread-10 ... Start Main count: ... 8 pool-1-thread-10. End Main Count: ... 9 pool-1-thread-10.
 Is over ... main thread end ...//The main thread ends after all threads have finished executing

The console waits 5 seconds to print out the top output, because all threads start with a concurrent operation and wait 5 seconds, so the overall look is only 5 seconds, which is a concurrent operation

Summarize:

1. The difference between the execute () method provided by Executorservice and the Submit () method:

A. The Execute () method only accepts instances of the runnable type, so you cannot get the return value or dynamically get the execution of the thread

B. The submit () method accepts the runnable and callable instances, returns the future instance, future The Get () method of the instance can fetch the thread execution return value and can throw the thread execution exception. So you can use the Submit () method if you want to get the result of the thread execution and can handle the exceptions that might occur when the thread executes, or if you want to cancel the thread execution in midstream

2. Through the output you can see that the main method (the main thread) ends after all threads have finished executing, because:

A. Get the future instance through the Submit () method and obtain the thread return result by future The Get () method of the instance, while the future instance's getting () method waits for the thread to finish before returning, so the main method waits for all child threads to end.

B. If you remove the for loop with the red callout above, the main method (the main thread) ends prematurely without waiting for all child threads to end

Add:

1. When multiple threads execute concurrently, if one of the threads has an exception and is not processed, the thread automatically stops executing, but the other threads execute normally, which is why Tomcat can continue to provide services when there is an exception to the Tomcat request.

2. Tomcat provides a thread pool and a wait pool, and each request is restarted with a new thread to process the request. If the thread pool is exhausted, the request is placed in the wait pool, and when the thread is released back into the threads pool, the thread processing request is allocated for the request in the waiting pool.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.