Java thread pool example

Source: Internet
Author: User

Java thread pool example

When we are doing a lot of highly concurrent applications, the bottleneck of a single thread cannot meet our needs. At this time, it is a conventional solution to use multithreading to increase the processing speed. When multithreading is used, we can use the thread pool to manage our threads. The advantages of using the thread pool are not mentioned.

This is also very important for thread security processing with multiple threads. Some students still need to make up more courses.

The Java thread pool is also simple. Let's briefly describe the inheritance relationship:
ThreadPoolExecutor extends actexecutorservice implements ExecutorService extends Executor

There is also an implementation class that supports delayed execution threads and repeated execution threads:
ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService

Let's figure out the related methods in these classes and use the thread pool to get down. In fact, it is enough to find out the functions of each method.
The most important thing is to sum up experience in practice. Enterprises need people who can actually solve problems.

The following is an example I wrote, including three Java files:
ExecutorServiceFactory. java
ExecutorProcessPool. java
ExecutorTest. java

The following code is provided:
1. ExecutorServiceFactory. java

Package com. test. threadpool; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. threadFactory; import java. util. concurrent. atomic. atomicInteger;/*** thread pool constructor ** @ author SHANHY (365384722@QQ.COM) * @ date December 4, 2015 */public class ExecutorServiceFactory {private static ExecutorServiceFactory executorFactory = new ExecutorServiceFactory (); /** * Scheduled task thread pool */private ExecutorService executors; private ExecutorServiceFactory () {}/ *** get ExecutorServiceFactory ** @ return */public static ExecutorServiceFactory getInstance () {return executorFactory ;} /*** create a thread pool, which can be scheduled to run commands or regularly after a given delay. ** @ Return */public ExecutorService createScheduledThreadPool () {// Number of CPUs int availableProcessors = Runtime. getRuntime (). availableProcessors (); // create executors = Executors. newScheduledThreadPool (availableProcessors * 10, getThreadFactory (); return executors;}/*** create a * Executor using a single worker thread to run this thread in the unbounded queue mode. (Note: If this single thread is terminated due to a failure during the execution before it is disabled, * if necessary, a new thread will execute subsequent tasks in place of it ). The tasks can be executed sequentially, and no threads are active at any given time. Unlike other equivalent * newFixedThreadPool (1), other threads can be used without the need to reconfigure the execution program returned by this method. ** @ Return */public ExecutorService createSingleThreadExecutor () {// create executors = Executors. newSingleThreadExecutor (getThreadFactory (); return executors;}/*** creates a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available. For programs that execute many short-term asynchronous tasks, these thread pools can usually improve program performance. Calling * execute will reuse the previously constructed thread (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 * seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note: You can use the ThreadPoolExecutor * constructor to create a thread pool with similar attributes but different details (such as timeout parameters. ** @ Return */public ExecutorService createCachedThreadPool () {// create executors = Executors. newCachedThreadPool (getThreadFactory (); return executors;}/*** creates a thread pool that can reuse a fixed number of threads and runs these threads in a shared unbounded queue. At any point, most nThreads * threads are in the active state of processing tasks. If you submit an additional task * when all threads are active, the additional task will wait in the queue before there is an available thread. If any thread is terminated due to a failure during execution before closing *, a new thread will execute subsequent tasks in place of it (if needed ). Before a thread is explicitly disabled, the thread in the pool will always exist. ** @ Return */public ExecutorService createFixedThreadPool (int count) {// create executors = Executors. newFixedThreadPool (count, getThreadFactory (); return executors;}/*** get the thread pool factory ** @ return */private ThreadFactory getThreadFactory () {return new ThreadFactory () {AtomicInteger sn = new AtomicInteger (); public Thread newThread (Runnable r) {SecurityManager s = System. getSecurityManager (); Thre AdGroup group = (s! = Null )? S. getThreadGroup (): Thread. currentThread (). getThreadGroup (); Thread t = new Thread (group, r); t. setName ("task thread-" + sn. incrementAndGet (); return t ;}};}}

2. ExecutorProcessPool. java

Package com. test. threadpool; import java. util. concurrent. callable; import java. util. concurrent. executorService; import java. util. concurrent. future;/*** thread processing class ** @ author SHANHY (365384722@QQ.COM) * @ date December 4, 2015 */public class ExecutorProcessPool {private ExecutorService executor; private static ExecutorProcessPool pool = new ExecutorProcessPool (); private final int threadMax = 10; private ExecutorProcessPool () {System. out. println ("threadMax >>>>>>" + threadMax); executor = ExecutorServiceFactory. getInstance (). createFixedThreadPool (threadMax);} public static ExecutorProcessPool getInstance () {return pool;}/*** close the thread pool. It should be noted that after the method of closing the thread pool is called, the thread pool will exit after all tasks in the queue are executed ** @ author SHANHY * @ date July 15, December 4, 2015 */public void shutdown () {executor. shutdown ();}/*** submit the task to the thread pool. You can receive the thread return value ** @ param task * @ return * @ author SHANHY * @ date July 15, December 4, 2015 */public Future
  Submit (Runnable task) {return executor. submit (task);}/*** submit the task to the thread pool, and you can receive the thread return value ** @ param task * @ return * @ author SHANHY * @ date December 4, 2015 */public Future
  Submit (Callable
  Task) {return executor. submit (task);}/*** submit the task directly to the thread pool, no return value ** @ param task * @ author SHANHY * @ date July 22, December 4, 2015 */public void execute (Runnable task) {executor.exe cute (task );}}

3. ExecutorTest. java

Package com. test. threadpool; import java. util. concurrent. callable; import java. util. concurrent. future; import java. util. concurrent. timeUnit;/*** test class *** @ author SHANHY (365384722@QQ.COM) * @ date December 4, 2015 */public class ExecutorTest {public static void main (String [] args) {ExecutorProcessPool pool = ExecutorProcessPool. getInstance (); for (int I = 0; I <200; I ++) {Future
  Future = pool. submit (new ExcuteTask1 (I + ""); // try {// If the returned value of the receiving thread is future. get () will be blocked. If such a write is executed by a thread and a thread. Therefore, it is not recommended to receive return values in special cases. // System. out. println (future. get (); //} catch (Exception e) {// e. printStackTrace (); //} for (int I = 0; I <200; I ++) {pool.exe cute (new ExcuteTask2 (I + ""));} // close the thread pool. If it is a thread pool that requires long-term running, you do not need to call this method. // When the listener exits, it is best to execute it. Pool. shutdown ();}/*** execute Task 1, realize Callable method ** @ author SHANHY (365384722@QQ.COM) * @ date December 4, 2015 */static class ExcuteTask1 implements Callable
  
   
{Private String taskName; public ExcuteTask1 (String taskName) {this. taskName = taskName ;}@ Override public String call () throws Exception {try {// The best hibernation Method for Java 6/7 is TimeUnit. MILLISECONDS. sleep (100); // it is best not to use Thread. sleep (100); TimeUnit. MILLISECONDS. sleep (int) (Math. random () * 1000); // a random number within 1000 milliseconds, simulating business logic processing} catch (Exception e) {e. printStackTrace ();} System. out. println ("------------- run the business logic here, Callable TaskName =" + taskName + "-------------"); return ">>>>>>>>>>>> thread return value, callable TaskName = "+ taskName +" <";}}/*** run Task 2, runable method ** @ author SHANHY (365384722@QQ.COM) * @ date December 4, 2015 */static class ExcuteTask2 implements Runnable {private String taskName; public ExcuteTask2 (String taskName) {this. taskName = taskName ;}@ Override public void run () {try {TimeUnit. MILLISECONDS. sleep (int) (Math. random () * 1000); // a random number within 1000 milliseconds, simulating business logic processing} catch (Exception e) {e. printStackTrace ();} System. out. println ("------------- run the business logic here, Runnable TaskName =" + taskName + "-------------");}}}
  

The above Code also has some annotations, and you can run the code yourself to see the effect.

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.