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

Source: Internet
Author: User

1. Class Executors
The executors class can be considered a "tool class". Invoke the introduction 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 methods:
(1) Create and return a method that sets the executorservice for a common configuration string.
(2) Create and return a method that sets the scheduledexecutorservice for a common configuration string.
(3) Creates and returns a "packaged" Executorservice method that disables reconfiguration by making the implementation-specific method inaccessible.
(4) Creates and returns a Threadfactory method that sets the newly created thread to a known state.
(5) Create and return callable methods that are not closed, so that they can be used in execution methods that require callable.
This class enables you to obtain instances of multiple thread pools, such as calling Newsinglethreadexecutor () to obtain a single-threaded Executorservice, calling Newfixedthreadpool () Get the Executorservice of the fixed size thread pool, and so on. Get Executorservice can do a lot of things, the simplest is to use it to execute Runnable objects, but also to implement some callable<t> objects. The thread's start () method does not return a value, and if it executes a method that has a return value, it is better to use Executorservice, optionally submit (), InvokeAll (), or invokeany (), Choose the appropriate method according to the specific situation.
Some of the methods provided 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. These thread pools generally improve program performance for programs that perform many short-term asynchronous tasks.

1.2 public static executorservice newfixedthreadpool (int nthreads)
Create a thread pool that reuses the number of fixed threads to 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.

These three methods can be used in conjunction with an instance of an interface threadfactory. and returns an instance of the Executorservice interface.
2. Interface Threadfactory
Create the object of the new thread as needed. Using a thread factory eliminates the need to manually write a call to new thread, allowing applications to use special lines to Cheng Zi classes, properties, 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 boot thread
4.1 Provides a simple thread to implement the Runnable interface
Mythread.java

Package com.zj.concurrency.executors;
 
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;}}

This thread will print out the appropriate creation and execution information.

4.2 Starting a thread using Cachedthreadpool
Cachedthreadpool.java

Package com.zj.concurrency.executors;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
 
public class Cachedthreadpool {public
  static void Main (string[] args) {
    Executorservice exec = EXECUTORS.NEWCA Chedthreadpool ();
    for (int i = 0; i < 5; i++)
      Exec.execute (new Mythread (i));
    Exec.shutdown ();
  }

Results:

Create Thread-0
Create Thread-1 Create
Thread-2
Create Thread-3
Thread-0 Run 1 time (s)
Thread-0 Run 2 time (s)
Thread-1 Run 1 time (s)
Thread-1 Run 2 time (s)
Thread-2 Run 1 time (s)
Thread-2 Run 2 time (s) C10/>create Thread-4
Thread-4 Run 1 (s)
Thread-4 Run 2 time (s)
Thread-3 Run 1 time (s)
Thread-3 ru N 2 time (s)


4.3 Starting a thread using Fixedthreadpool

Fixedthreadpool.java
package com.zj.concurrency.executors;
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 ();
  }

Results:

Create Thread-0
Create Thread-1 Create
Thread-2
Create Thread-3
create Thread-4
Thread-0 Run 1 Time (s)
Thread-0 run 2 (s)
Thread-2 Run 1 time (s)
Thread-2 Run 2 time (s)
Thread-3 Run 1 time (s)
T Hread-3 Run 2 time (s)
Thread-4 Run 1 time (s)
Thread-4 Run 2 time (s)
Thread-1 Run 1 time (s)
Thread-1 ru N 2 time (s)


4.4 Starting a thread using Singlethreadexecutor
Singlethreadexecutor.java

Package com.zj.concurrency.executors;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
 
public class Singlethreadexecutor {public
  static void Main (string[] args) {
    Executorservice exec = EXECUTORS.N Ewsinglethreadexecutor ();
    for (int i = 0; i < 5; i++)
      Exec.execute (new Mythread (i));
    Exec.shutdown ();
  }

Results:

Create Thread-0
Create Thread-1 Create
Thread-2
Create Thread-3
create Thread-4
Thread-0 Run 1 Time (s)
Thread-0 run 2 (s)
Thread-1 Run 1 time (s)
Thread-1 Run 2 time (s)
Thread-2 Run 1 time (s)
T Hread-2 Run 2 time (s)
Thread-3 Run 1 time (s)
Thread-3 Run 2 time (s)
Thread-4 Run 1 time (s)
Thread-4 ru N 2 time (s)

5. With the use of Threadfactory interface
we tried to add the daemon and priority property settings to the thread.
5.1 Setting Background thread properties
Daemonthreadfactory.java

Package com.zj.concurrency.executors.factory;
Import java.util.concurrent.ThreadFactory;
 
public class Daemonthreadfactory implements Threadfactory {public
  thread Newthread (Runnable r) {
    Thread t = new Thread (r);
    T.setdaemon (true);
    return t;
  }
}


5.2 Setting priority properties
Highest Priority Maxprioritythreadfactory.java

Package com.zj.concurrency.executors.factory;
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;
  }
}

Lowest priority Minprioritythreadfactory.java

Package com.zj.concurrency.executors.factory;
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 Start a thread with property settings
Execfromfactory.java

Package com.zj.concurrency.executors;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Com.zj.concurrency.executors.factory.DaemonThreadFactory;
Import Com.zj.concurrency.executors.factory.MaxPriorityThreadFactory;
 
Import Com.zj.concurrency.executors.factory.MinPriorityThreadFactory;  public class Execfromfactory {public static void main (string[] args) throws Exception {Executorservice defaultexec
    = 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 = i < i++) if (i = =) Maxpriorityexec.execute (new Mythread (i)); Elseif (i = =) Minpriorityexec.execute (new Mythread (i));
  else Defaultexec.execute (new Mythread (i));
 }
}

Result:

Create Thread-0 Create Thread-1 create Thread-2 create Thread-3 Thread-0 Run 1 time (s) Thread-0 Run 2 time (s) Thread-1 ru N 1 time (s) Thread-1 Run 2 time (s) Thread-2 Run 1 time (s) Thread-2 Run 2 time (s) Create Thread-4 Thread-4 Run 1 time (s) Th Read-4 Run 2 time (s) create Thread-5 Thread-5 Run 1 time (s) Thread-5 Run 2 time (s) Create Thread-6 create Thread-7 thread- 7 Run 1 time (s) Thread-7 Run 2 time (s) create Thread-8 Thread-8 Run 1 time (s) Thread-8 Run 2 time (s) Create Thread-9 creat 
E Thread-10 Thread-10 Run 1 (s) Thread-10 Run 2 time (s) Create Thread-11 Thread-9 Run 1 time (s) Thread-9 Run 2 time (s) Thread-6 Run 1 time (s) Thread-6 Run 2 time (s) Thread-3 Run 1 time (s) Thread-3 Run 2 time (s) Create Thread-12 create Threa D-13 Create Thread-14 Thread-12 Run 1 time (s) Thread-12 Run 2 time (s) Thread-13 Run 1 time (s) Thread-13 Run 2 time (s) Crea Te Thread-15 Thread-15 Run 1 (s) Thread-15 Run 2 time (s) Create Thread-16 Thread-16 Run 1 time (s) Thread-16 Run 2 time (s) Create Thread-17 CreAte Thread-18 Create Thread-19 Thread-14 Run 1 time (s) Thread-14 Run 2 time (s) Thread-17 Run 1 time (s) Thread-17 run 2 Tim E (s) Thread-18 run 1 (s) Thread-18 Run 2 time (s) Thread-19 Run 1 time (s) Thread-19 Run 2 time (s) Thread-11 Run 1 time (
 s) Thread-11 Run 2 time (s)

Related Article

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.