Use of threads and thread pools

Source: Internet
Author: User

Reference: http://www.cnblogs.com/dolphin0520/p/3932921.html

1. Threads: Looping new 10 threads

Note: A final defined variable can be used in the run () method

Package Com.test;public class Testthread {public static void main (string[] args) {for (int i =0; I <9; i++) {//final variable can be passed to the Run () method, final int task = I;new Thread (new Runnable () {@Overridepublic synchronized void run () {System.out.println ("task: "+ Task);}}). Start ();}}}

2. Thread pool

The direct use of Threadpoolexecutoris not advocated, and Java provides four thread pools through executors, respectively:


(1) 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.
(2) Newfixedthreadpool

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

Create a fixed-line pool that supports timed and recurring task execution.
(4) 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 following are examples of use of Newfixedthreadpool:

Package Com.test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class testexcutor {public static void main (string[] args) {//thread pool interface: executorserviceexecutorservice Fixthreadpool = Executors.newfixedthreadpool (5); for (int i=1; i<=5; i++) {Final int task =i;fixthreadpool.execute (new Runnable () {@ Overridepublic synchronized void Run () {for (int j=1; j<=3;j++) {System.out.println (Thread.CurrentThread (). GetName ( ) + "  +" task: "+ task +" Times   : "+j);}});} Fixthreadpool.shutdown ();}}

  

Use of threads and 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.