Java-----about the use of thread pools

Source: Internet
Author: User

The related concepts of threading are not described here, please Baidu or Google's

For learning threads, I think it is better to start from the code, the premise is that there is a certain accumulation of technology, otherwise please close no longer see ~

Four ways to implement thread pooling.

① cache thread Pool, flexible recycling of idle threads if the thread pool is longer than required for processing, new thread if not recyclable

 Packagethread;ImportJava.util.concurrent.Executor;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;//cacheable thread pool, if the thread pool length exceeds processing needs, can flexibly reclaim idle threads, if not recyclable, the new thread Public classThreadPoolExceutorTest1 { Public Static voidMain (string[] args) {Executorservice cachedthreadpoll=Executors.newcachedthreadpool ();  for(inti = 0; I < 10; i++) {            Final intindex = 1; Try{thread.sleep (index* 10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } cachedthreadpoll.execute (NewRunnable () { Public voidrun () {System.out.println (index);        }            }); }    }}

② Create a thread pool that can handle the maximum number of concurrent threads, and the threads will wait in the queue

 Packagethread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;//Create a thread pool that can handle the maximum number of concurrent threads, and the threads will wait in the queue Public classThreadPoolExecutorTest2 { Public Static voidMain (String []args) {Executorservice Fixedthreadpool=executors.newfixedthreadpool (3);  for(inti=0;i<10;i++) {            Final intIndex=1; Fixedthreadpool.execute (NewRunnable () { Public voidrun () {Try{System.out.println (index); Thread.Sleep (2000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }                }            }); }    }}

Create a thread pool that supports timed and recurring task execution, with deferred execution examples as follows (3m after execution)

 Packagethread;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledExecutorService;ImportJava.util.concurrent.TimeUnit;//Create a thread pool that supports timed and recurring task execution, with deferred execution examples as follows (3m after execution) Public classThreadPoolExecutorTest3 { Public Static voidMain (String []args) {Scheduledexecutorservice Scheduledthreadpool=executors.newscheduledthreadpool (5); Scheduledthreadpool.schedule (NewRunnable () { Public voidrun () {System.out.println ("This is 3 demo"); }        },3, Timeunit.milliseconds); }}

Periodic execution delay of 1 seconds after 3 seconds

 Packagethread;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledExecutorService;ImportJava.util.concurrent.TimeUnit;//periodic execution delay of 1 seconds after 3 seconds Public classThreadPoolExecutorTest35 { Public Static voidMain (String []args) {Scheduledexecutorservice Scheduledthreadpool=executors.newscheduledthreadpool (5); Scheduledthreadpool.scheduleatfixedrate (NewRunnable () { Public voidrun () {System.out.println ("This is 3 demo"); }        },1,3, Timeunit.milliseconds); }}

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).

 Packagethread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;//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 sample code is as follows Public classThreadPoolExecutorTest4 { Public Static voidmain (String [] args) {Executorservice singlethreadexecutor=Executors.newsinglethreadexecutor ();  for(inti=0;i<10;i++) {            Final intindex=i; Singlethreadexecutor.execute (NewRunnable () { Public voidrun () {Try{System.out.println (index); Thread.Sleep (2000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }                }            }); }    }}

 You can monitor the number of threads we create, run a non-terminating thread, and create a specified amount of threads by using the JDK's own monitoring tools to observe:

 Packagethread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;//You can monitor the number of threads we create, run a non-terminating thread, and create a specified amount of threads by using the JDK's own monitoring tools to observe: Public classThreadPoolExecutorTest45 { Public Static voidMain (string[] args) {Executorservice singlethreadexecutor=Executors.newcachedthreadpool ();  for(inti = 0; I < 100; i++) {            Final intindex =i; Singlethreadexecutor.execute (NewRunnable () { Public voidrun () {Try {                         while(true) {System.out.println (index); Thread.Sleep (10 * 1000); }                    } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();            }                }            }); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

 Open the JDK with your own monitoring tool Jdk-bin-jconsole.exe, run as Administrator

  

Threads can be viewed here ~, but the program must first run up ~

After the code is written ~ Do not understand can be hand-knocked a few times will deepen understanding

Java-----about the use of 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.