This mileage demonstrates how to use the built-in multi-threaded mechanism of JDK. A simple routine, with comments, demonstrates the method of using JDK to implement the thread pool and is suitable for beginners.
- Package com. cjt. thread. threadpool;
- Import java. util. Concurrent. executorservice;
- Import java. util. Concurrent. executors;
- Public class concurrent4threadpool {// class used to manage threads and provide thread services
- Private executorservice EXE = NULL; // Thread Pool
- Private Static final int pool_size = 4; // thread pool capacity
- Public concurrent4threadpool (){
- EXE = executors. newfixedthreadpool (pool_size); // create a thread pool
- System. Out. println ("the server is ready ...");
- }
- Public void server (){
- Int I = 0;
- While (I <100 ){
- Exe.exe cute (new worker (I); // run the thread pool
- I ++;
- }
- }
- Public static void main (string [] ARGs ){
- New concurrent4threadpool (). Server ();
- }
- Class worker implements runnable // work thread, the work to be done by the thread is implemented in this class
- {
- Int ID;
- Worker (int id ){
- This. ID = ID;
- }
- Public void run (){
- System. Out. println ("task" + ID + ": Start"); // the specific task
- }
- }
- }