Java thread Pool Detailed _java

Source: Internet
Author: User

The cost of booting a system is relatively high because it involves interacting with the operating system, and the benefit of using a thread pool is to improve performance, which can cause severe degradation of the system's performance and even cause the JVM to crash when the system contains a large number of concurrent threads. The maximum number of thread pool parameters can control the number of concurrent threads in the system.

The executors factory class is used to generate a thread pool, which contains several static factory methods to create the corresponding thread pool. The thread pool created is a Executorservice object that uses either the Submit method of the object or the Execute method to perform the corresponding runnable or callable task. The thread pool itself calls the shutdown () method to stop the thread pool when it is no longer needed, and when invoked, the thread pool will no longer allow the task to be added, but will not die until all the tasks that have been added have been completed.

1. Newcachedthreadpool () creates a thread pool with caching capabilities, the threads that are committed to the task (runnable or callable object) of the thread pool, and if the execution completes, is cached in the Cachedthreadpool for later tasks that need to be performed.

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

public class Cachethreadpool {
  static class Task implements Runnable {
    @Override public
    void Run () {
      Syst Em.out.println (This + "" + Thread.CurrentThread (). GetName () + "allstacktraces map size:"
          + Thread.CurrentThread (). g Etallstacktraces (). Size ());
    }

  public static void Main (string[] args) {
    Executorservice Cachethreadpool = Executors.newcachedthreadpool ();
    
    First add three tasks to the thread pool for
    (int i = 0; i < 3; i++) {
      cachethreadpool.execute (new Task);
    }
    
    After three threads have finished executing, add three more tasks to the thread pool
    try {
      thread.sleep (3000);
    } catch (Interruptedexception e) {
      E.printstacktrace ();
    }
    
    for (int i = 0; i < 3; i++) {
      cachethreadpool.execute (new Task ());}}



The results of the implementation are as follows:

CACHETHREADPOOL$TASK@2D312EB9 pool-1-thread-1 allstacktraces map Size:7
cachethreadpool$task@59522b86 pool-1-thread-3 allstacktraces map Size:7
cachethreadpool$task@73dbb89f pool-1-thread-2 AllStackTraces map Size:7
Cachethreadpool$task@5795cedc pool-1-thread-3 allstacktraces map Size:7
cachethreadpool$task@256d5600 pool-1-thread-1 allstacktraces map Size:7
cachethreadpool$task@7d1c5894 Pool-1-thread-2 allstacktraces Map Size:7

Thread objects in the thread pool are cached and reused when a new task executes. However, if you have a particularly large number of concurrent concurrency, the cache thread pool will still create many thread objects.

2, Newfixedthreadpool (int nthreads) creates a thread pool that specifies the number of threads that threads can reuse.

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

public class Fixedthreadpool {
  static class Task implements Runnable {
    @Override public
    void Run () {
      Syst Em.out.println (This + "" + Thread.CurrentThread (). GetName () + "allstacktraces map size:"
          + Thread.CurrentThread (). g Etallstacktraces (). Size ());
    }

  public static void Main (string[] args) {
    Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3);

    First add three tasks to the thread pool for
    (int i = 0; i < 5; i++) {
      fixedthreadpool.execute (new Task);
    }

    After three threads have finished executing, add three more tasks to the thread pool
    try {
      thread.sleep (3);
    } catch (Interruptedexception e) {
      E.printstacktrace ();
    }

    for (int i = 0; i < 3; i++) {
      fixedthreadpool.execute (new Task ());}}



Execution results:

fixedthreadpool$task@7045c12d pool-1-thread-2 allstacktraces map Size:7
FIXEDTHREADPOOL$TASK@50FA0BEF Pool-1-thread-2 allstacktraces map Size:7
fixedthreadpool$task@ccb1870 pool-1-thread-2 AllStackTraces map size:7< C3/>fixedthreadpool$task@7392b4e3 pool-1-thread-1 allstacktraces map Size:7
fixedthreadpool$task@5bdeff18 Pool-1-thread-2 allstacktraces map Size:7
fixedthreadpool$task@7d5554e1 pool-1-thread-1 AllStackTraces map Size:7
fixedthreadpool$task@24468092 pool-1-thread-3 allstacktraces map Size:7
fixedthreadpool$task@fa7b978 pool-1-thread-2 allstacktraces Map Size:7

3, Newsinglethreadexecutor (), create a single thread pool, equivalent to call Newfixedthreadpool (1)

4, Newsheduledthreadpool (int corepoolsize), creates a thread pool that specifies the number of threads that can be executed after a specified delay. You can also repeat a thread in one cycle, knowing that the call to shutdown () closes the pool.

Examples are as follows:

 import java.util.concurrent.Executors; import
Java.util.concurrent.ScheduledExecutorService;

Import Java.util.concurrent.TimeUnit; public class Scheduledthreadpool {static Class Task implements Runnable {@Override public void run () {S Ystem.out.println ("Time" + system.currenttimemillis () + "" + Thread.CurrentThread (). GetName () + "Allstacktraces map siz
    E: "+ thread.currentthread (). Getallstacktraces (). Size ()); } public static void Main (string[] args) {Scheduledexecutorservice Scheduledexecutorservice = Executors.newsch
    
    Eduledthreadpool (3);
    
    Scheduledexecutorservice.schedule (New Task (), 3, timeunit.seconds);
  
    Scheduledexecutorservice.scheduleatfixedrate (New Task (), 3, 5, timeunit.seconds);
    try {thread.sleep (30 * 1000);
    catch (Interruptedexception e) {e.printstacktrace ();
  } scheduledexecutorservice.shutdown (); }

}

The results of the operation are as follows:

Time 1458921795240 pool-1-thread-1 allstacktraces map size:6 time 1458921795241 pool-1-thread-2 AllStackTraces
map s Ize:6 time
1458921800240 pool-1-thread-1 allstacktraces map size:7 time
1458921805240 Allstacktraces map Size:7 time
1458921810240 pool-1-thread-1 allstacktraces map size:7 time
1458921815240 1-thread-1 allstacktraces Map size:7 time
1458921820240 pool-1-thread-1 allstacktraces map Size:7

As you can see from the runtime, the task is performed in a 5-second cycle.

5, Newsinglethreadscheduledexecutor () to create a thread pool with only one threads, with the call Newscheduledthreadpool (1).

Ii. Forkjoinpool and Forkjointask

Forkjoinpool is the implementation class of Executorservice, which supports dividing a task into several small task parallel computations, combining the results of several small tasks into the total calculation results. It has two constructors

Forkjoinpool (int parallelism) creates a forkjoinpool that contains parallelism parallel threads.

Forkjoinpool (), the Runtime.availableprocessors () method returns the value as the parallelism parameter to create the Forkjoinpool.

Forkjointask represents a task that can be parallel and merged. It is an abstract class that implements the Future<t> interface, which has two abstract subclasses, representing recuriveaction with no return value task and recursivetask with return values. These two abstract classes can be inherited according to specific requirements to implement their own objects, and then invoke the Forkjoinpool submit method execution.

Recuriveaction, for example, implements a parallel output of 0-300 digits.

Import Java.util.concurrent.ForkJoinPool;
Import java.util.concurrent.RecursiveAction;

Import Java.util.concurrent.TimeUnit; public class Actionforkjointask {static Class Printtask extends Recursiveaction {private static final int Threshol
    D = 50;
    private int start;

    private int end;
      Public printtask (int start, int end) {This.start = start;
    This.end = end; @Override protected void Compute () {if (End-start < THRESHOLD) {for (int i = start; I < End
        i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + i);
        } else {int middle = (start + end)/2;
        Printtask left = new Printtask (start, middle);
        Printtask right = new Printtask (middle, end);
        Left.fork ();
      Right.fork ();
    
    }} public static void Main (string[] args) {Forkjoinpool pool = new Forkjoinpool ();
    Pool.submit (New Printtask (0, 300)); try {pool.awaitTermination (2, timeunit.seconds);
    catch (Interruptedexception e) {e.printstacktrace ();
  } pool.shutdown ();

 }

}

After the small task is split, the fork () method of the task is invoked and joined to the Forkjoinpool in parallel execution.

Recursivetask example, implements a parallel calculation of 100 integer sums. Split into 20 numbers to obtain the results, at the end of the merge into the final result.

Import Java.util.Random;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ForkJoinPool;
Import Java.util.concurrent.Future;

Import Java.util.concurrent.RecursiveTask;  public class Taskforkjointask {static Class Caltask extends Recursivetask<integer> {private static final int

    THRESHOLD = 20;
    private int arr[];
    private int start;

    private int end;
      Public Caltask (int[] arr, int start, int end) {This.arr = arr;
      This.start = start;
    This.end = end;

      @Override protected Integer Compute () {int sum = 0;
        if (End-start < THRESHOLD) {for (int i = start, I < end; i++) {sum = Arr[i];
        } System.out.println (Thread.CurrentThread (). GetName () + "sum:" + sum);
      return sum;
        else {int middle = (start + end)/2;
        Caltask left = new Caltask (arr, start, middle);

        Caltask right = new Caltask (arr, middle, end); Left. fork ();

        Right.fork ();
      return Left.join () + Right.join ();
    }} public static void Main (string[] args) {int arr[] = new INT[100];
    Random Random = new Random ();

    int total = 0;
      for (int i = 0; i < arr.length i++) {int tmp = Random.nextint (20);
    Total + = (Arr[i] = tmp);

    } System.out.println ("Total" + total);

    Forkjoinpool pool = new Forkjoinpool (4);
    future<integer> Future = pool.submit (new Caltask (arr, 0, arr.length));
    try {System.out.println ("cal Result:" + future.get ());
    catch (Interruptedexception e) {e.printstacktrace ();
    catch (Executionexception e) {e.printstacktrace ();
  } pool.shutdown ();

 }

}

The results of the implementation are as follows:

Total 912
forkjoinpool-1-worker-2 sum:82
forkjoinpool-1-worker-2 sum:123
forkjoinpool-1-worker-2 sum : 144
forkjoinpool-1-worker-3 sum:119
forkjoinpool-1-worker-2 sum:106
forkjoinpool-1-worker-2
forkjoinpool-1-worker-2 sum:121
forkjoinpool-1-worker-3 sum:89
Cal result:912

After the subtasks have been executed, the join () method of the calling task gets the result of the subtask execution and adds the final result.

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.