Java thread pool: ExecutorService, Executors,
A simple Java thread pool can be obtained from Executors. newFixedThreadPool (int n. This method returns a thread pool with a thread capacity of n. ExecutorService execute.
An example is provided.
Package zhangphil.exe cutorservice; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class ZhangPhilExecutorService {// to easily understand the concept of a thread pool, assume that the capacity is only 2 of the thread pool. // More can be used in actual use! Private final int NUMBER = 2; public ZhangPhilExecutorService () {// create a thread pool with a capacity of 2. 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.exe cute (t);} // close the thread pool. Pool. shutdown ();} private class TestThread extends Thread {private int id; public TestThread (int id) {this. id = id ;}@ Overridepublic 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 ();}}
Output result:
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!
Zookeeper