Package csdn;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
/**
* @author Nineday
*/
public class Test {
public static void Main (String args[]) throws Interruptedexception {
Executorservice exe = Executors.newfixedthreadpool (50);
for (int i = 1; I <= 5; i++) {
Exe.execute (New Subthread (i));
}
Exe.shutdown ();
while (true) {
if (exe.isterminated ()) {
System.out.println ("It's over! ");
Break
}
Thread.Sleep (200);
}
}
}
The code above is the main thread, creating a thread pool that can execute 2 threads at the same time, and putting in 5 threads, and when all 5 threads have finished executing, print---"End! String
Exe.shutdown (); This method will not execute until the thread that joins the thread queue finishes executing.
Exe.isterminated (); executes after shutdown () or Shutdownnow () executes, and returns True.
Exe.isterminated () must be judged in the code above, or it will be printed directly after putting 5 threads into the thread pool: "Ended". Can not achieve the effect we want.
Through the while (true) cycle to determine the value of exe.isterminated () reborn, in order to prevent excessive judgment wasted resources, you can set the thread sleep Thread.Sleep (200);
It is because of this sleep that when all threads in the thread pool are executed, it is possible to delay 200ms before the "end" statement is executed. The smaller the delay of this parameter, the more accurate the result.
The following is a child thread, and the child thread simply prints out the number i;
[Java] View plaincopy
Package csdn;
/**
* @author Nineday
*/
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 Result:
[Plain] View plaincopy
Run
3
1
4
5
2
It's over!
Build successfully (Total time: 2 seconds)
The execution order of the sub-threads cannot be controlled, so the result of the output is disorderly.
How Java determines if all the thread pool tasks are done