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