Demo for Java thread pool app

Source: Internet
Author: User

In a lot of high concurrency applications, single-threaded bottlenecks have not satisfied our needs, the use of multi-threading to improve processing speed is a more conventional solution. When using multithreading, we can use the thread pool to manage our threads, and the advantages of using the thread pool are not much to say.

The Java thread pool is simple to say, simply saying the inheritance relationship:
Threadpoolexecutor extends Abstractexecutorservice implements Executorservice extends Executor

There is also an implementation class that supports deferred execution threads and can execute threads repeatedly:
Scheduledthreadpoolexecutor extends Threadpoolexecutor implements Scheduledexecutorservice

By figuring out the relevant methods in these classes, using the thread pool is a Cinch. In fact, it is enough to figure out the functions of each method.
The most important thing is to sum up experience in practice, enterprises need to be able to solve the problem of the actual Person.

Here is an example of what I wrote, including 3 Java files, namely:
Executorservicefactory.java
Executorprocesspool.java
Executortest.java

1, executorservicefactory

 packagetest;Importjava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.ThreadFactory;Importjava.util.concurrent.atomic.AtomicInteger;/*** Thread Pool construction Factory * *@authorAllan * @date March 20, 2017*/ public classExecutorservicefactory {Private StaticExecutorservicefactory executorfactory =Newexecutorservicefactory (); /*** Timed task thread pool*/    PrivateExecutorservice executors; Privateexecutorservicefactory () {}/*** Get executorservicefactory * *@return     */     public Staticexecutorservicefactory getinstance () {returnexecutorfactory; }    /*** Create a thread pool that can schedule commands to run after a given delay or perform them on a regular basis. *      * @return     */     publicExecutorservice createscheduledthreadpool () {//Number of CPUs        intAvailableprocessors =runtime.getruntime (). availableprocessors (); //CreateExecutors = Executors.newscheduledthreadpool (availableprocessors * 10, Getthreadfactory ()); returnexecutors; }    /*** 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 perform the subsequent task if needed). Each task is guaranteed to be executed sequentially, and no more than one thread is active at any given Time.     Unlike other equivalent * Newfixedthreadpool (1), it is guaranteed to use other threads without reconfiguring the executing program returned by this Method. *      * @return     */     publicExecutorservice createsinglethreadexecutor () {//CreateExecutors =Executors.newsinglethreadexecutor (getthreadfactory ()); returnexecutors; }    /*** 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.     Note that you can use the Threadpoolexecutor * Construction method to create a thread pool with similar attributes but with different details (for example, timeout parameters). *      * @return     */     publicExecutorservice createcachedthreadpool () {//CreateExecutors =Executors.newcachedthreadpool (getthreadfactory ()); returnexecutors; }    /*** Create a thread pool that can reuse a fixed number of threads to run them in a shared, unbounded Queue. At any point, most nthreads * threads are in the active state of the processing Task. If you submit an additional task * when all threads are active, the additional task waits in the queue until the thread is Available. If any thread terminates * during execution due to failure during shutdown, a new thread will perform the subsequent task (if Necessary) instead of it.     A thread in the pool will persist until a thread is explicitly closed. *      * @return     */     publicExecutorservice Createfixedthreadpool (intCount) {        //CreateExecutors =Executors.newfixedthreadpool (count, getthreadfactory ()); returnexecutors; }    /*** Get thread pool Factory * *@return     */    Privatethreadfactory getthreadfactory () {return Newthreadfactory () {atomicinteger sn=NewAtomicinteger ();  publicThread newthread (Runnable r) {securitymanager s=System.getsecuritymanager (); Threadgroup Group= (s! =NULL) ?s.getthreadgroup (): thread.currentthread (). getthreadgroup (); Thread T=NewThread (group, r); T.setname ("task thread-" +Sn.incrementandget ()); returnt;    }        }; }}

2, Executorprocesspool

 packagetest;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutorService;Importjava.util.concurrent.Future;/*** Thread Processing class * *@authorAllan * @date March 20, 2017*/ public classExecutorprocesspool {PrivateExecutorservice executor; Private StaticExecutorprocesspool pool =NewExecutorprocesspool (); Private Final intThreadmax = 10; Privateexecutorprocesspool () {System.out.println ("threadmax>>>>>>>" +threadmax); Executor=executorservicefactory.getinstance (). Createfixedthreadpool (threadmax); }     public StaticExecutorprocesspool getinstance () {returnpool; }    /*** Close the thread pool, and Here's the point: when the thread pool method is called, the thread pool executes all the tasks in the queue before exiting *@authorAllan * @date March 20, 2017*/     public voidshutdown () {executor.shutdown (); }    /*** Submit a task to the thread pool, you can receive the return value of the threads * *@paramTask *@return     * @authorAllan * @date March 20, 2017*/     publicFuture<?>Submit (Runnable Task) {returnExecutor.submit (task); }    /*** Submit a task to the thread pool, you can receive the return value of the threads * *@paramTask *@return     * @authorAllan * @date March 20, 2017*/     publicFuture<?> Submit (callable<?>Task) {        returnExecutor.submit (task); }    /*** Submit task directly to thread pool, no return value * *@paramTask *@authorAllan * @date March 20, 2017*/     public voidExecute (Runnable task) {executor.execute (task); }}

3, Executortest

 packagetest;Importjava.util.concurrent.Callable;Importjava.util.concurrent.Future;Importjava.util.concurrent.TimeUnit;/*** Test class * *@authorAllan * @date March 20, 2017*/ public classExecutortest { public Static voidmain (string[] Args) {executorprocesspool pool=executorprocesspool.getinstance ();  for(inti = 0; I < 200; i++) { future<?> future = Pool.submit (NewExcuteTask1 (i+ ""));//try {//if the receive thread returns a value, future.get () is blocked if it is a thread that is executed by one Thread. therefore, It is not recommended to use the receive return value for Non-special Cases. //System.out.println (future.get ()); //} catch (Exception E) {//e.printstacktrace ();//          }        }         for(inti = 0; I < 200; i++) {pool.execute (NewExcuteTask2 (i+ "")); }        //Close the thread pool, if it is a thread pool that needs to run for a long time, without calling the Method. //it is best to execute the listener when it exits. Pool.shutdown (); }    /*** Perform task 1, implement callable mode * *@authorAllan * @date March 20, 2017*/    Static classExcuteTask1ImplementsCallable<string> {        PrivateString taskname;  publicExcuteTask1 (String Taskname) { this. TaskName =taskname; } @Override publicString Call ()throwsException {Try {//the best sleep method for Java 6/7 is TimeUnit.MILLISECONDS.sleep (+);//It is best not to use Thread.Sleep (+);TimeUnit.MILLISECONDS.sleep ((int) (math.random () * 1000));//random numbers within 1000 milliseconds, simulating business logic processing}Catch(Exception E) {e.printstacktrace (); } System.out.println ("-------------execute business logic here, callable TaskName =" + taskname + "-------------"); return">>>>>>>>>>>>> thread return value, callable TaskName =" + taskname + "<<<<< <<<<<<<<< "; }    }    /*** Perform task 2, implement runable mode * *@authorAllan * @date March 20, 2017*/    Static classExcuteTask2ImplementsRunnable {PrivateString taskname;  publicExcuteTask2 (String Taskname) { this. TaskName =taskname; } @Override public voidRun () {Try{TimeUnit.MILLISECONDS.sleep (int) (math.random () * 1000));//random numbers within 1000 milliseconds, simulating business logic processing}Catch(Exception E) {e.printstacktrace (); } System.out.println ("-------------execute business logic here, Runnable taskname =" + taskname + "-------------"); }    }}

Original: http://blog.csdn.net/catoop/article/details/50180949

Another recommendation: the difference between submit and execute in Executorservice

Demo for Java thread pool app

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.