JAVA Multithreading and Concurrent Learning notes (iii)

Source: Internet
Author: User

Using the Executors class to create and manage thread usage in Java concurrent programming

 1. Class Executors
The executors class can be seen as a "tool class". Cited in the JDK1.6 API:

Factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package. This class supports the following various methods:

    • Creates and returns a method that sets the executorservice of a common configuration string.
    • Creates and returns a method that sets the scheduledexecutorservice of a common configuration string.
    • Creates and returns a "wrapped" Executorservice method that disables reconfiguration by making the implementation-specific method inaccessible.
    • Creates and returns a Threadfactory method that sets the newly created thread to a known state.
    • A method that creates and returns a callable in the form of a non-closed packet, which can be used in an execution method that requires callable.

This class enables you to obtain instances of multiple thread pools, such as the ability to invoke Newsinglethreadexecutor () to obtain a single thread of Executorservice, calling Newfixedthreadpool () Get the Executorservice of the fixed size thread pool, and so on. Get Executorservice can do more things, the simplest is to use it to execute the Runnable object, you can also perform some of the objects that implement callable<t>. The start () method with thread does not return a value, and if the thread executes a method that has a return value then it is better to use Executorservice, either submit (), InvokeAll (), or invokeany (), Select the appropriate method according to the specific situation. some of the methods available in this class are:

1.1 public static Executorservice Newcachedthreadpool ()
Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are available. For programs that perform many short-term asynchronous tasks, these thread pools can often improve program performance.

1.2 public static Executorservice newfixedthreadpool (int nthreads)
Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded queue.

1.3 public static Executorservice Newsinglethreadexecutor ()
Create a Executor that uses a single worker thread to run the thread in a unbounded queue.

2. Interface Threadfactory  

Create the object for the new thread as needed. Using a thread factory eliminates the need to manually write calls to the new thread, allowing applications to use special line Cheng Zi classes, attributes, and so on. The simplest implementation of this interface is:

Class Simplethreadfactory implements Threadfactory {public  Thread Newthread (Runnable r) {   return new Thread (R);  } }

  

3. Interface Executorservice

This interface provides a way to manage termination.


4. Create a standard thread pool start thread


 4.1 Provides a simple thread to implement the Runnable interface

public class MyThread implements Runnable {  private int count = 1, number;    public MyThread (int num) {number    = num;    System.out.println ("Create thread-" + number);  }    public void Run () {    while (true) {      System.out.println ("thread-" + number + "Run" + count+ "time (s)");      if (++count = = 3)       return;}}}  

  4.2 Starting a thread with Cachedthreadpool

Import Java.util.concurrent.executorservice;import java.util.concurrent.Executors;  public class Cachedthreadpool {public  static void Main (string[] args) {    Executorservice exec = Executors.newcach Edthreadpool ();    for (int i = 0; i < 5; i++)      Exec.execute (new MyThread (i));    Exec.shutdown ();  }}

  

4.3 Starting a thread with Fixedthreadpool

Import Java.util.concurrent.executorservice;import java.util.concurrent.Executors;  public class Fixedthreadpool {public  static void Main (string[] args) {    Executorservice exec = Executors.newfix Edthreadpool (2);    for (int i = 0; i < 5; i++)      Exec.execute (new MyThread (i));    Exec.shutdown ();  }}

  

4.4 Starting a thread with Singlethreadexecutor

Import Java.util.concurrent.executorservice;import java.util.concurrent.Executors;  public class Singlethreadexecutor {public  static void Main (string[] args) {    Executorservice exec = executors.new Singlethreadexecutor ();    for (int i = 0; i < 5; i++)      Exec.execute (new MyThread (i));    Exec.shutdown ();  }}

  

5. Use with the Threadfactory interface


Set the background thread property to the thread join daemon and Priority property settings, set the Precedence property

Import java.util.concurrent.ThreadFactory;  public class Maxprioritythreadfactory implements Threadfactory {public  Thread Newthread (Runnable r) {    thread t = new Thread (r);    T.setpriority (thread.max_priority);    return t;  

  

Import java.util.concurrent.ThreadFactory;  public class Daemonthreadfactory implements Threadfactory {public  Thread Newthread (Runnable r) {    Thread t = new T Hread (r);    T.setdaemon (true);    return t;  }}

  

Lowest-priority import Java.util.concurrent.ThreadFactory;  public class Minprioritythreadfactory implements Threadfactory {public  Thread Newthread (Runnable r) {    Thread t = New Thread (R);    T.setpriority (thread.min_priority);    return t;  }}

 5.3 Starting a thread with property settings

Import Java.util.concurrent.executorservice;import java.util.concurrent.Executors;  public class Execfromfactory {public  static void Main (string[] args) throws Exception {    Executorservice defaulte Xec = Executors.newcachedthreadpool ();    Executorservice daemonexec = Executors       . Newcachedthreadpool (New Daemonthreadfactory ());    Executorservice maxpriorityexec = Executors       . Newcachedthreadpool (New Maxprioritythreadfactory ());    Executorservice minpriorityexec = Executors       . Newcachedthreadpool (New Minprioritythreadfactory ());    for (int i = 0; i < i++)      Daemonexec.execute (new MyThread (i));    for (int i = ten; i <; i++)      if (i = =)       Maxpriorityexec.execute (new MyThread (i));      else if (i = =)       Minpriorityexec.execute (new MyThread (i));      else       Defaultexec.execute (new MyThread (i));}  }

  

Reference article:

1. Java multi-Threading and concurrency

2. Use of the Java thread pool

JAVA Multithreading and Concurrent Learning notes (iii)

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.