|
A simple Java thread pool can be obtained from Executors.newFixedThreadPool (int n). This method returns a thread pool with thread capacity n. ExecutorService then the implementation of the execute.
An example is given.
Package zhangphil.executorservice;
Import java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Public class ZhangPhilExecutorService {
/ / In order to easily understand the concept of thread pool, assuming the capacity of only 2 thread pool.
// The actual course of the course can be more!
Private final int NUMBER = 2;
Public ZhangPhilExecutorService () {
/ / Create a capacity of 2 thread pool.
ExecutorService pool = Executors.newFixedThreadPool (NUMBER);
For (int i = 0; i < 10; i ++) {
Thread t = new TestThread (i);
System.out.println ( "thread pool execution thread id:" + i);
Pool.execute (t);
}}
// Close the thread pool.
Pool.shutdown ();
}}
Private class TestThread extends Thread {
Private int id;
Public TestThread (int id) {
This.id = id;
}}
@Override
Public void run () {
System.out.println ( "thread:" + id + "-> run ...");
Try {
Thread.sleep (5000);
} Catch (Exception e) {
E.printStackTrace ();
}}
System.out.println ( "thread:" + id + "-> end!");
}}
}}
Public static void main (String [] args) {
New ZhangPhilExecutorService ();
}}
}}
Run the output:
Thread pool execution thread id: 0
Thread pool execution thread id: 1
Thread pool execution thread id: 2
Thread pool execution thread id: 3
Thread: 0 -> run ...
Thread pool execution thread id: 4
Thread: 1 -> Run ...
Thread pool execution thread id: 5
Thread pool execution thread id: 6
Thread pool execution thread id: 7
Thread pool execution thread id: 8
Thread pool execution thread id: 9
Thread: 1 -> End!
Thread: 0 -> End!
Thread: 2 -> run ...
Thread: 3 -> run ...
Thread: 3 -> End!
Thread: 2 -> End!
Thread: 4 -> Run ...
Thread: 5 -> run ...
Thread: 4 -> End!
Thread: 5 -> End!
Thread: 6 -> run ...
Thread: 7 -> Run ...
Thread: 7 -> End!
Thread: 6 -> End!
Thread: 8 -> run ...
Thread: 9 -> Run ...
Thread: 9 -> End!
Thread: 8 -> End! |
|
|
|