Four types of Java thread pool usage parsing _java

Source: Internet
Author: User

This article analyzes four kinds of Java thread pool usage for everyone's reference, the specific contents are as follows

1, the drawbacks of new thread

Perform an asynchronous task are you still just the following new thread?

New Thread (New Runnable () {

  @Override public
  void Run () {
    //TODO auto-generated method stub
    }
  }
). Start ();

Then you are out too much, the disadvantages of new thread are as follows:

A. New thread creates poor performance each time.
B. Threads lack unified management, may create unlimited new threads, compete with each other, and may consume excessive system resources causing panic or oom.
C. Lack of additional functionality, such as timed execution, regular execution, and thread disruption.

The benefits of the four thread pools offered by the new Thread,java are:

A. Reusing existing threads, reducing the overhead of object creation, extinction, and good performance.
B. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, avoid congestion.
C. Provide functions such as timed execution, regular execution, single thread, concurrent number control.

2. Java thread Pool

Java provides four thread pools through executors, respectively:

Newcachedthreadpool creates a cacheable thread pool that, if the thread pool length exceeds the processing needs, is flexible enough to reclaim idle threads and, if not recyclable, create a new thread.
Newfixedthreadpool creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded wait in the queue.
Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
Newsinglethreadexecutor creates a single-threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are performed in the specified order (FIFO, LIFO, priority).
(1) Newcachedthreadpool:

Creates a cacheable thread pool that, if the thread pool length exceeds processing needs, is flexible enough to reclaim idle threads and, if not recyclable, create a new thread. The sample code is as follows:

Executorservice Cachedthreadpool = Executors.newcachedthreadpool ();
  for (int i = 0; i < i++) {
    final int index = i;
  try {
    Thread.Sleep (index * 1000);
  } 
    catch (Interruptedexception e) {
      e.printstacktrace ();
  }

Cachedthreadpool.execute (New Runnable () {

@Override public
void Run () {
  System.out.println (index);
}
});
}

The thread pool is infinite, and the first task is completed when the second task is performed, and the thread that executes the first task is reused instead of creating a new thread at a time.

(2) Newfixedthreadpool:

Creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded wait in the queue. The sample code is as follows:

Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3);
  for (int i = 0; i < i++) {
  final int index = i;

  Fixedthreadpool.execute (New Runnable () {

@Override public
void Run () {
try {
  System.out.println () index);
  Thread.Sleep ();
} catch (Interruptedexception e) {
  //TODO auto-generated catch block
  e.printstacktrace ();
  }}}
);
}

Because the thread pool size is 3, each task outputs index sleep 2 seconds, so print 3 digits every two seconds.

The size of the fixed-length pool is best set according to system resources. such as Runtime.getruntime (). Availableprocessors (). Refer to Preloaddatacache.

(3) Newscheduledthreadpool:

Create a fixed-line pool that supports timed and recurring task execution. The deferred execution sample code is as follows:

Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5);
 Scheduledthreadpool.schedule (New Runnable () {

@Override public
void Run () {
  System.out.println () Delay 3 seconds ");
}
, 3, timeunit.seconds);

Indicates a delay of 3 seconds for execution.

Execute the sample code regularly as follows:

Scheduledthreadpool.scheduleatfixedrate (New Runnable () {

@Override public
void Run () {
  SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");
}
, 1, 3, timeunit.seconds);

Indicates that the delay is performed every 3 seconds after 1 seconds.

Scheduledexecutorservice is safer and more powerful than a timer.

(4) Newsinglethreadexecutor:

Creates a single-threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are performed in the specified order (FIFO, LIFO, priority). The sample code is as follows:

Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor ();
for (int i = 0; i < i++) {
final int index = i;
Singlethreadexecutor.execute (New Runnable () {

@Override public
void Run () {
  try {
    SYSTEM.OUT.PRINTLN (index);
  Thread.Sleep ();
} catch (Interruptedexception e) {
  //TODO auto-generated catch block
  e.printstacktrace ();
    }}}
  );
}

The results are output sequentially, which is equivalent to performing each task sequentially.

Most of the current GUI programs are single-threaded. Android single-threaded can be used for database operations, file operations, application of bulk installations, application of bulk deletions, etc. that are not suitable for concurrent but possibly IO blocking and affect UI thread responses.

The role of the thread pool:

The thread pool function is to limit the number of threads executing in the system.
According to the environment of the system, can automatically or manually set the number of threads to achieve the best effect of the operation, less waste of system resources, many caused the system congestion efficiency is not high. The thread pool controls the number of threads, and other threads wait in line. A task completes, and the first task from the queue is executed. If there is no waiting process in the queue, this resource in the thread pool is waiting. When a new task needs to be run, it can start running if there is a waiting worker thread in the thread pool, otherwise enter the wait queue.

Why do I use a thread pool:

1. The number of times to create and destroy threads is reduced, and each worker thread can be reused to perform multiple tasks.

2. According to the system's affordability, adjust the number of threads in the thread pool, to prevent the use of excessive memory, and the server tired down (each thread needs about 1MB of memory, the more threads open, the consumption of memory will be larger, the last crash).

The top-level interface in the Java thread pool is executor, but in the strictest sense executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice.

Some of the more important classes:

Executorservice: The true thread pool interface.

Scheduledexecutorservice: Can be similar to Timer/timertask to solve problems that require repetitive tasks.

The default implementation of the Threadpoolexecutor:executorservice.

Scheduledthreadpoolexecutor: Inherits the Threadpoolexecutor Scheduledexecutorservice interface implementation, the periodic task scheduling class realization.

It is more complicated to configure a thread pool, especially if the thread pool is not clearly understood, it is likely that the configured thread pool is not superior, so there are some static factories in the executors class that generate some common thread pools.

1.newSingleThreadExecutor

Create a single-threaded thread pool. This thread pool has only one threads working, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, then there is a new thread to replace it. This thread pool guarantees that the order in which all tasks are performed is performed in the order in which they are submitted.

2.newFixedThreadPool

Create a fixed size thread pool. Create a thread each time a task is committed, until the thread reaches the maximum size of the thread pool. The size of the thread pool will remain unchanged once it reaches its maximum value, and if a thread ends up executing an exception, the thread pool complements a new thread.

3.newCachedThreadPool

Create a cacheable pool of threads. If the thread pool is larger than the threads needed to process the task,

A thread that is partially idle (60 seconds without a task) is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the thread pool size, and the thread pool size is entirely dependent on the maximum threading size that the operating system (or JVM) can create.

4.newScheduledThreadPool

Create a thread pool of infinite size. This thread pool supports the need for timing and periodic execution of tasks.

Instance Code

A fixed size thread pool, Newfixedthreadpool:

Package app.executors; 

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

/** 
 * java thread: Thread pool 
 * 
 * @author Xiho 
/public class Test {public 
  static void Main (string[] args) { 
    //Create a thread pool of reusable fixed thread number 
    Executorservice pool = executors.newfixedthreadpool (2); 
    Create threads thread 
    t1 = new Mythread (); 
    Thread t2 = new Mythread (); 
    Thread t3 = new Mythread (); 
    Thread T4 = new Mythread (); 
    Thread T5 = new Mythread (); 
    Put the thread into the pool for execution 
    pool.execute (t1); 
    Pool.execute (T2); 
    Pool.execute (T3); 
    Pool.execute (T4); 
    Pool.execute (T5); 
    Close the thread pool 
    pool.shutdown () 
  ; 
} 

Class Mythread extends Thread { 
  @Override public 
  void Run () { 
    System.out.println thread.currentthread ( ). GetName () + "is executing ... "); 
  } 
}

Output results:

Pool-1-thread-1 is executing ... 
pool-1-thread-3 is executing ... 
pool-1-thread-4 is executing ... 
pool-1-thread-2 is executing ... 
pool-1-thread-5 is executing ...

Change the parameters in Executorservice pool = Executors.newfixedthreadpool (5): Executorservice pool = Executors.newfixedthreadpool (2), The output results are:

Pool-1-thread-1 is executing ... 
pool-1-thread-1 is executing ... 
pool-1-thread-2 is executing ... 
pool-1-thread-1 is executing ... 
pool-1-thread-2 is executing ...

From the results above, it can be seen that the Newfixedthreadpool parameters specify the maximum number of threads that can be run, and that the number of lines beyond this Chengga will not run. Second, the threads that join the thread pool belong to the managed state, and the thread's operation is not affected by the order of accession.

Second, single task thread pool, Newsinglethreadexecutor:

Simply change the Executorservice pool = Executors.newfixedthreadpool (2) in the above code to Executorservice pool = Executors.newsinglethreadexecutor ();
Output results:

Pool-1-thread-1 is executing ... 
pool-1-thread-1 is executing ... 
pool-1-thread-1 is executing ... 
pool-1-thread-1 is executing ... 
pool-1-thread-1 is executing ...

As you can see, every time you call the Execute method, you end up calling the Thread-1 run method.

Third, the variable size of the thread pool, Newcachedthreadpool:

Similar to the above, just change the way the pool is created: executorservice pool = Executors.newcachedthreadpool ();

Output results:

Pool-1-thread-1 is executing ... 
pool-1-thread-2 is executing ... 
pool-1-thread-4 is executing ... 
pool-1-thread-3 is executing ... 
pool-1-thread-5 is executing ...

This approach is characterized by the need to create a thread pool of new threads as needed, but reuse them when previously constructed threads are available.

Four, delay connection pool, Newscheduledthreadpool:

public class Testscheduledthreadpoolexecutor {public

  static void Main (string[] args) {

    Scheduledthreadpoolexecutor exec = new Scheduledthreadpoolexecutor (1);

    Exec.scheduleatfixedrate (New Runnable () {///The exception is triggered at intervals

           @Override

           publicvoid Run () {

              //throw new RuntimeException ();

              System.out.println ("================");

           }

         , 1000, 5000, timeunit.milliseconds);

    Exec.scheduleatfixedrate (New Runnable () {//print system time at intervals to prove that the two are not affecting each other

           @Override

           publicvoid Run () {

              System.out.println (System.nanotime ());

           }

         , 1000, Watts, timeunit.milliseconds);

  }



Output results:

================

8384644549516

8386643829034

8388643830710

================

8390643851383

8392643879319

8400643939383

The above is the entire content of this article, I hope to help you learn.

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.