Java Learning (10): Java thread pool instance

Source: Internet
Author: User
Tags terminates

The thread pool resolves two different issues: because of the reduced overhead of each task invocation, they typically provide enhanced performance when performing a large number of asynchronous tasks, and can also provide methods for binding and managing resources, including the threads used to execute the task set. Each Threadpoolexecutor also maintains some basic statistical data, such as the number of completed tasks.

There are four thread pools commonly used in Java. Executors.newCachedThreadPool()(no boundary pool, automatic thread recycling), Executors.newFixedThreadPool(int) (fixed size thread pool), Executors.newSingleThreadExecutor() (single background thread), andThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)

1. Executors.newCachedThreadPool() (no boundary pool, can be automated Process recovery)

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. Calling Execute reuses the previously constructed thread, if the thread is available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources.

2. Executors.newFixedThreadPool(int nThreads) (fixed size thread pool)

Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded queue. At any point, most nthreads threads are in the active state of the processing task. If additional tasks are committed while all threads are active, the additional task waits in the queue until there are available threads. If any thread terminates due to a failure during execution prior to shutdown, a new thread will perform subsequent tasks (if necessary) instead of it. A 关闭 thread in the pool will persist until a thread has been explicitly put in place.

3. Executors.newSingleThreadExecutor() (single background thread)

Create a Executor that uses a single worker thread to run the thread in a unbounded queue. (Note that if this single thread is terminated because of a failure during the execution of the shutdown, a new thread will replace it for subsequent tasks if needed). Each task is guaranteed to be executed sequentially, and no more than one thread is active at any given time.

4.ThreadPoolExecutor (int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue< Runnable> WorkQueue, Rejectedexecutionhandler handler)

The threadpoolexecutor will getCorePoolSize() getMaximumPoolSize() automatically adjust the pool size based on the boundaries set by Corepoolsize (see) and maximumpoolsize (see). When a new task is committed in a method execute(java.lang.Runnable) , if the running thread is less than corepoolsize, a new thread is created to process the request, even if the other worker threads are idle. If you run more threads than corepoolsize and less than maximumpoolsize, a new thread is created only when the queue is full. If you set the same corepoolsize and Maximumpoolsize, a fixed-size thread pool is created. If you set Maximumpoolsize to a basic unbounded value (such as Integer.max_value), the pool is allowed to accommodate any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set based on constructs, but can also be used setCorePoolSize(int) and setMaximumPoolSize(int) dynamically changed.

If there are currently more than corepoolsize threads in the pool, these extra threads will terminate when the idle time exceeds KeepAliveTime This provides a way to reduce resource consumption when the pool is inactive.

all BlockingQueue can be used to transfer and keep committed tasks. You can use this queue to interact with the pool size: If you run fewer threads than Corepoolsize, Executor always prefers to add new threads without queuing. If you are running a thread that is equal to or more than corepoolsize, Executor always prefers to join the request to the queue without adding a new thread. If the request cannot be queued, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is rejected.

There are three common strategies for queuing:

(1) Submit directly. The default option for the Task Force column is SynchronousQueue that it will submit the task directly to the thread without keeping them. Here, if there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be constructed. This policy avoids locking when processing a set of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows the possibility of an increase in the number of lines that are allowed to continue when the command arrives in a row that exceeds the average that the queue can handle.

(2) Unbounded queue. Using unbounded queues (for example, without a predefined capacity LinkedBlockingQueue ) will cause all corepoolsize threads to be busy waiting in the queue. This way, the created thread will not exceed corepoolsize. (therefore, the value of the maximumpoolsize is not valid.) When each task is completely independent of other tasks, that is, when task execution does not affect each other, it is appropriate to use a unbounded queue, for example, in a Web page server. This queueing can be used to handle transient burst requests, which allow the possibility of an increase in the number of lines that are allowed to occur when the command reaches an average of more than the queue can handle.

(3) Bounded queue. When using limited maximumpoolsizes, bounded queues (such as ArrayBlockingQueue ) help prevent resource exhaustion, but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.

A limited boundary is used for the maximum thread and work queue capacity, and new tasks submitted in the method are rejected when the queued task is saturated execute(java.lang.Runnable) . In both cases, theexecute method calls its RejectedExecutionHandler RejectedExecutionHandler.rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor) method. The following four predefined handler policies are available:

(1) in the default ThreadPoolExecutor.AbortPolicy , the handler is rejected and the runtime is thrown RejectedExecutionException .

(2) in ThreadPoolExecutor.CallerRunsPolicy , the thread calls the execute itself that runs the task, which is equivalent to calling the run () method directly.

(3) in ThreadPoolExecutor.DiscardPolicy , the tasks that cannot be performed are deleted.

(4) in ThreadPoolExecutor.DiscardOldestPolicy , if the execution program has not been closed, the task that is in the head of the work queue is deleted, and then the program is retried (repeat this process if it fails again).

Code examples are as follows

1 ImportJava.text.SimpleDateFormat;2 Importjava.util.Date;3 ImportJava.util.concurrent.ArrayBlockingQueue;4 ImportJava.util.concurrent.ThreadPoolExecutor;5 ImportJava.util.concurrent.TimeUnit;6 7  Public classMyThreadextendsThread8 {9     PrivateString name;Ten      One     Private StaticSimpleDateFormat DF =NewSimpleDateFormat ("HH:mm:ss"); A      -      PublicMyThread (String name) -     { the          This. Name =name; -     } -      -      Public voidRun () +     { -         Try +         { ASystem.out.println ("Thread" + This. Name + ":" + Df.format (NewDate ())); atThread.Sleep (1000);//increase code Execution time -         } -         Catch(interruptedexception e) -         { - e.printstacktrace (); -         } in     } -      to      Public Static voidMain (string[] args) +     { -         //generates a thread pool. Number of core threads 3, max threads 5, Idle thread reclaim time 1000ms, block queue Length 5, new task discard after queue full theThreadpoolexecutor ThreadPool = *             NewThreadpoolexecutor (3, 5, Timeunit.milliseconds,NewArrayblockingqueue<runnable> (5), $                 NewThreadpoolexecutor.discardpolicy ());Panax NotoginsengThreadpool.execute (NewMyThread ("01"));//when you need to return a result, use the Submit -Threadpool.execute (NewMyThread ("02")); theThreadpool.execute (NewMyThread ("03")); +Threadpool.execute (NewMyThread ("04")); AThreadpool.execute (NewMyThread ("05")); theThreadpool.execute (NewMyThread ("06")); +Threadpool.execute (NewMyThread ("07")); -Threadpool.execute (NewMyThread ("08")); $Threadpool.execute (NewMyThread ("09")); $Threadpool.execute (NewMyThread ("10")); -Threadpool.execute (NewMyThread ("11")); -Threadpool.execute (NewMyThread ("12")); the          -     }Wuyi}
View Code

Print results

1 thread 01:12:49:25 2 thread 03:12:49:25 3 thread 10:12:49:25 4 thread 02:12:49:25
    
      5 thread 09:12:49:25
      6 thread 04:12:49:26
      7 thread 05:12:49:26
      8 thread 06:12:49:26
     
       9 thread 07:12:49:26
      ten thread 08:12:49:26
     
    
View Code

When you add 12 tasks in a sequence,

(1) The first three directly create thread execution;

(2) 4-8 of these 5 tasks queued for execution in queue;

(3) because the queue is full and maximumpoolsize=5, Task 9, 10 create thread execution (the number of bus path is less than or equal to maxsize), 11, 12 is discarded directly;

(4) 1, 2, 3, 9, 10 task execution end, the task in the queue execution;

(5) After execution, the two threads are terminated after the timeout period (1000ms), and the surviving thread remains corepoolsize=3 size, even if there are no tasks at this time.

Java Learning (10): Java thread pool instance

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.