Java Executorservice Simple use of four thread pools

Source: Internet
Author: User
Tags thread class

We all know that creating a thread can inherit the thread class or implement the Runnable interface, and the actual thread class implements the Runnable interface.

Until today to understand the role of the post-thread: We can open threads to perform some more time-consuming operations, similar to the front-end Ajax asynchronous operations, such as the user upload a large file, we can get to the file after the opening of a thread to operate the file, but can be returned in advance, If synchronous processing can be too time consuming, it affects system availability.

1. The disadvantage of new thread

How the native open thread executes the asynchronous task:

New Thread (new  Runnable () {    @Override    publicvoid  run () {           TODO auto-generated method stub    }}). Start ();

The disadvantages are as follows:

    • The new thread creates a poor performance each time.
    • Threads lack unified management, may have unlimited new threads, compete with each other, and may consume too much system resources to cause a crash or oom.
    • 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:

    • Reuse the existing threads, reduce the cost of object creation, extinction, performance is good.
    • Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, to avoid clogging.
    • Provides functions such as timed execution, periodic execution, single-threaded, concurrency control, and more.

Use of the 2.Java thread pool

Java provides four thread pools through executors, namely:
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.
Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads 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 executed in the specified order (FIFO, LIFO, priority).

 The return value can be accepted with Executorservice, Executorservice is an interface to inherit executor, Threadpoolexecutor inherits from Abstractexecutorservice, Abstractexecutorservice implements the Executorservice interface. It is also commonly used as a static member variable for a class, with all instances sharing a Executorservice object.

Mythread Thread class: Inherits the thread and overrides the Run method, where the Run method prints one second at a time

 Packagecn.qlq.threadTest;/*** Native Thread class Thread usage method *@authorAdministrator **/ Public classMyThreadextendsThread {/*** Change thread name * *@paramThreadName*/     PublicMyThread (String threadname) { This. SetName (ThreadName); } @Override Public voidrun () { for(inti=0;i<5;i++) {System.out.println (GetName ()+"-------"+i); Try{Thread.Sleep (1*1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }}

Usage of 1.FixedThreadPool

Creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.

To create a method:

    /**      *     parameter is the size of the initialized thread pool */    privatestaticfinal Executorservice Batchtaskpool = Executors.newfixedthreadpool (2);

View Source:(using a blocking queue, a thread that exceeds the pool capacity waits in the queue)

Test code:

 Packagecn.qlq.threadTest;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classFixedthreadpooltest {/*** parameter is the size of the initialized thread pool*/    Private Static FinalExecutorservice Batchtaskpool = Executors.newfixedthreadpool (2);  Public Static voidMain (string[] args) { for(inti = 0;i < 3;i++) {Batchtaskpool.execute (NewMyThread ("MT" +i)); }    }    }

Results:

MT1-------0
Mt0-------0
Mt0-------1
MT1-------1
MT1-------2
Mt0-------2
MT1-------3
Mt0-------3
MT1-------4
Mt0-------4
MT2-------0
MT2-------1
MT2-------2
MT2-------3
MT2-------4

Explain:

Pool capacity is 2, so mt0 and MT1 can be added to the thread pool, MT2 is only temporarily added to the wait queue, such as Mt0 or MT1 after the completion of the queue after the removal of MT2 the opportunity to execute ...

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

2.CachedThreadPool

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.

To create a method:

Private Static Final Executorservice Batchtaskpool = Executors.newcachedthreadpool ();

View Source:(using the synchronization queue)

Test code:

 Packagecn.qlq.threadTest;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classCachedthreadpooltest {Private Static FinalExecutorservice Batchtaskpool =Executors.newcachedthreadpool ();  Public Static voidMain (string[] args) { for(inti = 0;i < 3;i++) {Batchtaskpool.execute (NewMyThread ("MT" +i)); }    }    }

Results:

Mt0-------0
MT1-------0
MT2-------0
Mt0-------1
MT1-------1
MT2-------1
Mt0-------2
MT1-------2
MT2-------2
MT1-------3
Mt0-------3
MT2-------3
MT1-------4
Mt0-------4
MT2-------4

3.SingleThreadExecutor usage

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). Similar to the effect of single-threaded execution.

To create a method:

    Private Static Final Executorservice Batchtaskpool = Executors.newsinglethreadexecutor ();

View source; Blocking queue used

Test code:

 Packagecn.qlq.threadTest;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classSinglethreadexecutortest {Private Static FinalExecutorservice Batchtaskpool =Executors.newsinglethreadexecutor ();  Public Static voidMain (string[] args) { for(inti = 0;i < 3;i++) {Batchtaskpool.execute (NewMyThread ("MT" +i)); }    }    }

Results:

Mt0-------0
Mt0-------1
Mt0-------2
Mt0-------3
Mt0-------4
MT1-------0
MT1-------1
MT1-------2
MT1-------3
MT1-------4
MT2-------0
MT2-------1
MT2-------2
MT2-------3
MT2-------4

4.ScheduledThreadPool usage------can realize task scheduling function

Creates a fixed-length pool (which specifies the capacity initialization size) to support timed and recurring task executions. You can implement a one-time execution delay task, or you can perform periodic tasks.

To create a method:

    Private Static Final Scheduledexecutorservice Batchtaskpool = Executors.newscheduledthreadpool (2);

View Source:(using delay queue)

Test code:

 Packagecn.qlq.threadTest;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledExecutorService;ImportJava.util.concurrent.TimeUnit; Public classScheduledthreadpooltest {Private Static FinalScheduledexecutorservice Batchtaskpool = Executors.newscheduledthreadpool (2);  Public Static voidMain (string[] args) { for(inti = 0; I < 3; i++) {            //The first execution is performed after 3s (delayed task)Batchtaskpool.schedule (NewMyThread ("my" + i), 3, Timeunit.seconds); //The first parameter is the task that needs to be performed, the second parameter is the first delay time, the third parameter is the interval of two executions, and the fourth parameter is the unit of timeBatchtaskpool.scheduleatfixedrate (NewMyThread ("my" + i), 3,7, Timeunit.seconds); //The first parameter is the task that needs to be performed, the second parameter is the first delay time, the third parameter is the interval of two executions, and the fourth parameter is the unit of timeBatchtaskpool.schedulewithfixeddelay (NewMyThread ("my" + i), 3,5, Timeunit.seconds); }    }}

Schedule is a one-time task that can specify a delay.
Scheduleatfixedrate a fixed frequency to perform a program (Task)
Schedulewithfixeddelay a relatively fixed delay after the execution of a plan (this is the first task after the execution of 5s again, the general use of this method of task scheduling)

About the difference between the two:

Scheduleatfixedrate: This is done at a fixed time, simply put: Point execution
Schedulewithfixeddelay: This, is to wait for a fixed time after the last task, and then execute. Simply put: Perform the previous task before executing

Example Child

Scheduledthreadpool.scheduleatfixedrate (New Tasktest ("Perform dispatch task 3"), 0, 1, timeunit.seconds); This is every 1 seconds, a new thread is opened
Scheduledthreadpool.schedulewithfixeddelay (New Tasktest ("fourth One"), 0, 3, timeunit.seconds); This is the last task, 3 seconds after the start of a new thread

Of course, the implementation of task scheduling can also be implemented using quartz framework, more flexible. Reference: https://www.cnblogs.com/qlqwjy/p/8723358.html

For example, an example of a excutorservice used in my system:

/*** Synchronize nail organization structure and People's action * *@authorAdministrator **/@Namespace ("/sync") Public classSyncgroupanduserandbaseinfoactionextendsDmsactionsupport {/*** Serialid*/    Private Static Final LongSerialversionuid = 3526083465788431949L; Private Static FinalExecutorservice Batchtaskpool = Executors.newfixedthreadpool (2); Private StaticLogger Logger = Loggerfactory.getlogger (syncgroupanduserandbaseinfoaction.class); @AutowiredPrivateGroupanduserservice Groupservice; @AutowiredPrivateBaseinfoservice Baseinfoservice; /*** Synchronize the data of the basic information * *@return     */@Action (Value= "Syncgroupanduser")     PublicString Syncgroupanduser () {LongStartTime =System.currenttimemillis (); Logger.info ("Manual sync groups and users!"); String Accesstoken=Fetchdatautils.getaccesstoken (); if(Stringutils.isblank (Accesstoken)) {Setprejs ("Accesstoken is null!"); return"JS"; } String groupstr=fetchdatautils.getgroupstr (Accesstoken); if(Stringutils.isblank (groupstr)) {Setprejs ("Groupstr is null"); return"JS"; } Set<String> dinggroupids = Fetchdatautils.getgroupids (GROUPSTR);//nails synchronized back to the group//open a new thread to get nails users and organizationsBatchdisposedinggroupanduser (Dinggroupids,groupstr,accesstoken); Map<String,Object> response =NewHashmap<string,object>(); Response.put ("Success",true); Response.put ("Message", "Success Sync datas!");                Setprejs (Apiutils.getjsonresultfrommap (response)); LongEndTime =System.currenttimemillis (); Logger.info ("Synchronous nail structure and user completion-----time: {}ms", (endtime-startTime)); return"JS"; }    Private voidBatchdisposedinggroupanduser (FinalSet<string> Dinggroupids,FinalString Groupstr,FinalString Accesstoken) {Runnable Run=NewRunnable () {@Override Public voidrun () {groupservice.batchdisposegroups (groupstr, dinggroupids);                            Groupservice.fetchanddisposeusers (Accesstoken, dinggroupids);        }        };    Batchtaskpool.execute (run); }    }

Attention:

The formal parameter of the Batchdisposedinggroupanduser () method must be declared final or compiled incorrectly.

Java Executorservice Simple use of four thread pools

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.