Java thread pool

Source: Internet
Author: User

Disadvantages of New Thread:

1 New Thread (new  Runnable () {23    @Override4public       void  run () {5         //  TODO auto-generated method Stub 6     }7 }). Start ();

The disadvantages of new thread are as follows:

A. Each new thread creates a poor performance for the newly created object.
B. Lack of unified management of threads, the possibility of unlimited new threads, competing with each other, and potentially consuming excessive system resources can lead to freezing or oom.
C. Lack of additional functionality, such as timed execution, periodic execution, and thread interruption.
The benefits of the four thread pools provided by new Thread,java are:
A. Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created.
B. Improve response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.
C. High-threading manageability. Threads are scarce resources that, if created indefinitely, not only consume system resources, but also reduce system stability, using a thread pool for uniform allocation, tuning, and monitoring.

You can create a thread pool from Threadpoolexecutor:

1      PublicThreadpoolexecutor (intCorepoolsize,2                               intMaximumpoolsize,3                               LongKeepAliveTime,4 timeunit Unit,5Blockingqueue<runnable>workQueue) {6          This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,7 executors.defaultthreadfactory (), defaulthandler);8}

Corepoolsize (basic size of the thread pool): When a task is submitted to the thread pool, the line pool creates a thread to perform the task, and the thread is created even if other idle basic threads are able to perform new tasks, and is no longer created until the number of tasks that need to be executed is larger than the thread pool base size. If the thread pool's Prestartallcorethreads method is called, the thread pool creates and starts all basic threads in advance.

Maximumpoolsize (maximum thread pool size): The maximum number of threads allowed to be created by a thread pool. If the queue is full and the number of threads that have been created is less than the maximum number of threads, the thread pool will then create new threads to perform the task. It is worth noting that if you use the unbounded task queue This parameter has little effect.

KeepAliveTime (thread activity hold time): When the worker thread of the thread pool is idle, the time to remain alive. So if the task is a lot, and each task executes a short time, you can adjust the time to increase the utilization of the thread.

Timeunit (unit of thread activity hold time): Optional units have day (days), hours (HOURS), minutes (MINUTES), milliseconds (MILLISECONDS), microseconds (microseconds, 1 per thousand milliseconds), and nanoseconds ( nanoseconds, 1 per thousand microseconds).

Runnabletaskqueue (Task queue): A blocking queue that is used to hold tasks waiting to be executed.

Arrayblockingqueue: is a bounded blocking queue based on the array structure, which sorts the elements in FIFO (first-out) principle.

Linkedblockingqueue: A blocking queue based on a linked list structure, which sorts elements in FIFO (first-out), with throughput typically higher than arrayblockingqueue. The static Factory Method Executors.newfixedthreadpool () uses this queue.

Synchronousqueue: A blocking queue that does not store elements. Each insert operation must wait for another thread to invoke the remove operation, or the insert operation will always be in a blocked state, with throughput typically higher than linkedblockingqueue, and the static factory method Executors.newcachedthreadpool Use this queue.

Priorityblockingqueue: An infinite-blocking queue with a priority.

Threadfactory: Used to set the factory for creating threads, you can set a more meaningful name for each thread created by the thread factory.

Rejectedexecutionhandler (Saturation policy): When the queue and thread pool are full, indicating that the thread pools are saturated, a policy must be taken to handle the new tasks that are submitted. This policy is abortpolicy by default, indicating that an exception is thrown when a new task cannot be processed. The following are the four strategies provided by JDK1.5.

AbortPolicy: Throws an exception directly.

Callerrunspolicy: Runs the task only with the caller's thread.

Discardoldestpolicy: Discards the most recent task in the queue and executes the current task.

Discardpolicy: not processed, discarded.

It is also possible to implement the Rejectedexecutionhandler interface customization strategy According to the application scenario. Tasks such as logging or persistence that cannot be processed.

Java provides four thread pools through executors, namely:
Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.

Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.

Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.

The bottom of them is threadpoolexecutor.


Newfixedthreadpool:

1  Public Static Executorservice newfixedthreadpool (int  nthreads) {2         returnnew Threadpoolexecutor (Nthreads, Nthreads,3                                       0L, Timeunit.milliseconds,4                                        New linkedblockingqueue<runnable>()); 5     }

The size of the corepoolsize and Maximumpoolsize is the same, because the maximumpoolsize parameter is meaningless if the unbounded queue is used

Blockingqueue chose Linkedblockingqueue, the queue has a characteristic that he is unbounded.

1Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3);2  for(inti = 0; I < 10; i++) {3     Final intindex =i;4Fixedthreadpool.execute (NewRunnable () {5 6 @Override7          Public voidrun () {8             Try {9 System.out.println (index);TenThread.Sleep (2000); One}Catch(interruptedexception e) { A                 //TODO auto-generated Catch block - e.printstacktrace (); -             } the         } -     }); -}

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

The size of a fixed-length pool is best set based on system resources. such as Runtime.getruntime (). Availableprocessors ().

Newsinglethreadexecutor:

 1  public  static   Executorservice Newsinglethreadexecutor () { 2  return  new   Finalizabledelegatedexecutorservice  3  (new  threadpoolexecutor (1, 1 4  0l 5  new  linkedblockingqueue<r Unnable> 6 } 

Equivalent to Newfixedthreadpool (1)

1Executorservice Singlethreadexecutor =executors.newsinglethreadexecutor ();2  for(inti = 0; I < 10; i++) {3     Final intindex =i;4Singlethreadexecutor.execute (NewRunnable () {5 6 @Override7          Public voidrun () {8             Try {9 System.out.println (index);TenThread.Sleep (2000); One}Catch(interruptedexception e) { A                 //TODO auto-generated Catch block - e.printstacktrace (); -             } the         } -     }); -}

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

Most of the current GUI programs are single-threaded.

Newcachedthreadpool:

1  Public Static Executorservice Newcachedthreadpool () {2         return New Threadpoolexecutor (0, Integer.max_value,3                                       60L, Timeunit.seconds,4                                        New synchronousqueue<runnable>()); 5     }

The first is the unbounded thread pool, so we can find Maximumpoolsize as Max. Next blockingqueue use Synchronousqueue on the selection: Each insert operation must wait for the corresponding removal of another thread.

For example, I add an element first, and then if you continue to try to add it will block until another thread takes an element and vice versa. (That is, the producer-consumer model with a buffer of 1)

1Executorservice Cachedthreadpool =Executors.newcachedthreadpool ();2  for(inti = 0; I < 10; i++) {3     Final intindex =i;4     Try {5Thread.Sleep (Index * 1000);6}Catch(interruptedexception e) {7 e.printstacktrace ();8     }9 TenCachedthreadpool.execute (NewRunnable () { One  A @Override -          Public voidrun () { - System.out.println (index); the         } -     }); -}

The thread pool is infinitely large, and when the first task is completed when the second task is performed, the threads that perform the first task are reused instead of each new thread.

Newscheduledthreadpool:

1      Public StaticScheduledexecutorservice Newscheduledthreadpool (intcorepoolsize) {2         return NewScheduledthreadpoolexecutor (corepoolsize);3     }4 5      PublicScheduledthreadpoolexecutor (intcorepoolsize) {6         Super(Corepoolsize, Integer.max_value, 0, nanoseconds,7               Newdelayedworkqueue ());8}

1 scheduledexecutorservice scheduledthreadpool = Executors.newscheduledthreadpool (5); 2 scheduledthreadpool.schedule (new  Runnable () {34    @Override  5public     void  run () {6         System.out.println (" Delay 3 seconds "); 7     }8 }, 3, timeunit.seconds);

  Represents a delay of 3 seconds for execution.

Scheduledthreadpool.scheduleatfixedrate (new  Runnable () {    @Override    public  void  Run () {        System.out.println ("Delay 1 seconds, and excute every 3 seconds");     1, 3, timeunit.seconds);

Represents a delay of 1 seconds after every 3 seconds.

Scheduledexecutorservice is safer and more powerful than a timer.

Java thread pool

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.