After Java 5, a large number of multi-threaded interfaces were provided. Previously, the thread pool was simply used, and the Future mode was also found recently.
Only some code is pasted:
Definition pool:
1. private static final ExecutorService worker = Executors. newFixedThreadPool (N); // Thread Pool
2. private static List
Use thread pool:
1. futureList. add (worker. submit (this ));
End thread:
1. // end the thread execution (interrupted) in the thread pool)
2. public static void cancel (){
3. for (Future f: futureList ){
4. f. cancel (true );
5 .}
6 .}
Note: Future is the thread execution result ticket. When Callable is used for execution, the thread execution result f. get () can be obtained, and the end and execution status of a thread can be controlled. When Runnable is used for execution, the result is null, but the thread can also be controlled.
Supplement:
The Thread interrupt method Thread. currentThread () should be called (). Interrupt (); but does not end the subthread as immediately as the stop method, but changes the interrupted semaphore Thread. interrupted (), an InterruptedException exception will be thrown in the blocked thread, but the sub-thread will continue to execute under non-blocking conditions. You need to determine the semaphore in the loop to throw an exception.
Author: xi_hong_shi