For more information visit the thread www.itkc8.com
Thread Pool Tools:
import java.util.concurrent.*;
public class CommonThreadPool {
private static ExecutorService exec = new ThreadPoolExecutor(50, 100, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10000),
new ThreadPoolExecutor.CallerRunsPolicy());
public static void execute(Runnable command) {
exec.execute(command);
}
// the sub-thread execution Future.get end () return null, if not finished, the main thread will block waiting for
public static Submit Future (the Runnable Command) {return exec.submit (Command);}
// Returns the child thread can be obtained from the value returned in the future: Future.get ();
public static Submit Future (a Callable Command) {
return exec.submit (Command);
}
}
test classes:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class ThreadTest {
@Test
public void ThreadTest() {
List<Future> futureList = new ArrayList<>();
for(int i = 0; i < 4; i++) {
int finalI = i;
Future future = CommonThreadPool.submit(() -> {
try {
System.out.println(finalI + " 我执行了。。。");
Thread.sleep(5000L);
System.out.println(finalI + " 我执行完了。。。");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
futureList.add(future);
}
// main thread work on something else, let the child thread to execute asynchronously.
MainThreadOtherWork ();
System.out.println ( "Waiting Sub now the Thread DONE.");
// main thread other work completed, waiting for the end of child thread, call future.get () series of methods can be.
//
{the try
for (Future Future: futureList) {
System.out.println (Future.get ());
}
} the catch (InterruptedException | ExecutionException E) {
e.printStackTrace ();
}
the try {
System.out.println ( "Processing a. ");
the Thread.sleep (1000);
System.out.println (" process two ");.
the Thread.sleep (1000);
System.out.println (" processing three ");.
the Thread.sleep (1000 );
System.out.println ( "four process.");
the Thread.sleep (1000);
System.out.println ( "all processing is complete.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static void mainThreadOtherWork Private () {
System.out.println ( "main thread to work");
the try {
the Thread.sleep (2000L);
} the catch (InterruptedException E) {
e.printStackTrace ();
}
System.out.println ( "finished the main thread");
}
}
The results:
The main thread start working
0 I performed. . .
2 I performed. . .
3 I performed. . .
1 I performed. . .
The main thread finished the job
waits for the child thread.
2 I finished execution. . .
3 I finished execution. . .
1 I finished execution. . .
0 I finished execution. . .
null
null
null
null
process a.
treatment of titanium.
Processing III.
Processing IV.
All the processing is completed.