Original address: http://blog.csdn.net/truong/article/details/40227435
public class Test {public
static void Main (String args[]) throws interruptedexception {
executorservice exe = EXE Cutors.newfixedthreadpool (m);
for (int i = 1; I <= 5; i++) {
exe.execute (new Subthread (i));
Exe.shutdown ();
while (true) {
if (exe.isterminated ()) {
System.out.println () is finished. ");
break;
Thread.Sleep (+);
}
}
Above is the code of the main thread, creating a thread pool that can execute 50 threads at the same time, and putting in 5 threads, and printing---when all 5 threads have finished executing. String
Exe.shutdown (); This method will not execute until the thread that joins the thread queue finishes executing.
Exe.isterminated () is executed only after shutdown () or Shutdownnow () is executed, and returns TRUE.
Exe.isterminated () must be judged in the above code, or it will print directly after putting 5 threads into the thread pool: "End." Can not achieve the effect we want.
The value of exe.isterminated () is judged by a while (true) loop, and the thread Sleep Thread.Sleep (200) can be set to prevent excessive judgment wasting resources.
It is because of this sleep that when all threads in all thread pools have finished executing, it is possible to delay 200ms before executing the "end" statement. The smaller the delay, the more accurate the result.
The following is a child thread, and the child thread simply prints the number I;
public class Subthread extends thread{
private final int i;
Public subthread (int i) {
this.i = i;
}
@Override public
Void Run () {
System.out.println (i);
}
}
Execution results:
3
1
4
5
2
ended.
Successful build (Total time: 2 seconds)
The execution order of the child threads is not controllable, so the result of the output is scrambled. ==============================================================================================