Java Multithreading-thread pool

Source: Internet
Author: User

The fourth way to get a thread: The thread pool, a executorservice, uses several possible pool threads to perform each submitted task, typically using the Executors factory method configuration.

The thread pool can address 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 binding and management resources, including execution
The task set is used by the thread) method. Each threadpoolexecutor also maintains some basic statistical data, such as the number of completed tasks.

For ease of use across a wide range of contexts, this class provides a number of adjustable parameters and extension hooks (hooks). However, programmers are strongly advised to use the more convenient executors factory approach:

    1. Executors.newcachedthreadpool () (No boundary pool, automatic thread recovery is possible)
    2. Executors.newfixedthreadpool (int) (fixed size thread pool)
    3. Executors.newsinglethreadexecutor () (single background thread)

They all pre-defined settings for most usage scenarios.

Thread pool wrapper class (used in Android development):

 PackageCom.company;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.ScheduledExecutorService;ImportJava.util.concurrent.TimeUnit;/*** @ class Name: Threadutils * Description: TODO (thread Pool tool Class) * @ Author: soyoungboy*/ Public classThreadutils {Private Static volatileThreadutils instance =NULL; //Private constructor Suppresses    Privatethreadutils () {} Public Staticthreadutils getinstance () {//if already inited, no need to get lock everytime        if(Instance = =NULL) {            synchronized(Threadutils.class) {                if(Instance = =NULL) {instance=Newthreadutils (); }            }        }        returninstance; }    /*** Initialize the number of threads, to be verified by history, temporarily get 4*/     PublicExecutorservice ThreadPool = Executors.newfixedthreadpool (4); /*** Single Thread*/    StaticExecutorservice Singlethreadpool =Executors.newsinglethreadexecutor (); /*** Perform deferred tasks, like the effect of a timer*/     PublicScheduledexecutorservice Schedulethreadpool = Executors.newscheduledthreadpool (2); /*** Perform tasks immediately * *@paramtask Threadutils.getinstance (). Excute (run); */     Public voidExcute (Runnable Task) {Threadpool.execute (Task); }    /*** Single-threaded operation, mainly used for read/write asynchronous operation of database * *@paramtask Threadutils.getinstance (). Excutesinglethread (run); * @return     */     PublicFuture Excutesinglethread (Runnable Task) {returnSinglethreadpool.submit (Task);    }    ; /*** Delayed Execution of tasks * *@paramTask *@paramdelay Threadutils.getinstance (). Schedule (run,1000); */     Public voidSchedule (Runnable task,Longdelay)    {schedulethreadpool.schedule (task, delay, timeunit.milliseconds); }    /**     * @returnvoid return type * @Title: Shutdownthreadpool * @Description: TODO ()*/     Public voidShutdownthreadpool () {threadpool.shutdownnow (); }    /**     * @returnvoid return type * @Title: Shutdownthreadpool * @Description: TODO ()*/     Public voidShutdownschedulethreadpool () {schedulethreadpool.shutdownnow (); }    /**     * @returnvoid return type * @Title: Shutdownsinglethreadpool * @Description: TODO (single thread pool destroy operation)*/     Public voidShutdownsinglethreadpool () {singlethreadpool.shutdownnow (); }}

Demo:

 Public classTestscheduledthreadpool { Public Static voidMain (string[] args)throwsException {threadutils instance=threadutils.getinstance ();  for(inti = 0; I < 10; i++) {instance.schedule ()- {                intnum =NewRandom (). Nextint (100);//Generate random numbersSystem.out.println (Thread.CurrentThread (). GetName () + ":" +num); }, 3);    } instance.shutdownschedulethreadpool (); }}

Results:

Pool-3-thread-2: -3-thread-1pool: -3-thread-2 pool: -3-thread-1:Pool -3-thread-2:0Pool-3-thread-1: -3-thread-2: Pool -3-thread-1:the pool -3-thread-2: -3-thread-1: 15

Java Multithreading-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.