Overview
Callable Introduction See: http://blog.csdn.net/zengmingen/article/details/53288119
Multithreading introduction See: Http://blog.csdn.net/zengmingen/article/details/53284999
Code Taskcallable.java
Package multithreading.pool;
Import java.util.concurrent.Callable;
public class Taskcallable implements callable<string>{
/** thread number
/private int tNo;
Public taskcallable (int tNo) {
this.tno=tno;
}
@Override public
String call () throws Exception {
string Tname=thread.currentthread (). GetName ();
Long Currenttimemillis = System.currenttimemillis ();
System.out.println (tno+ "-" +tname+ "Start Time is:" +currenttimemillis/1000);
try {
thread.sleep;
} catch (Interruptedexception e) {
e.printstacktrace ();
}
System.out.println (tno+ "-" +tname+ "is working ...");
Return ' The thread is ' +tno
}
}
Testpool.java
package Multithreading.pool;
Import java.util.ArrayList;
Import java.util.List;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future; public class Testpool {public static void main (string[] args) throws Exception, executionexception {list<future& Lt
String>> futures = new arraylist<future<string>> ();
Executorservice Newfixedthreadpool = Executors.newfixedthreadpool (2);
for (int i = 0; i < 5; i++) {future<string> Future = newfixedthreadpool.submit (new taskcallable (i));
Futures.add (future);
///print result for (future<string> f:futures) {Boolean done = F.isdone (); It can be seen from the order in which the results are printed, even if they are not completed, blocking waiting System.out.println (done?).
"Completed": "Incomplete");
Get results from future, this method is blocked until the thread task returns the result System.out.println ("Completed thread returns future result:" + f.get ());
} newfixedthreadpool.shutdown (); }
}
Run Results
0-pool-1-thread-1 Start Time is:1479808023
Not completed
1-pool-1-thread-2 Start Time is:1479808023
0-pool-1-thread-1 is working ...
1-pool-1-thread-2 is working ...
Finished thread returns future result: the thread is 0
has been completed
Finished thread returns future result: the thread is 1
Not completed
2-pool-1-thread-1 Start Time is:1479808024
3-pool-1-thread-2 Start Time is:1479808024
3-pool-1-thread-2 is working ...
2-pool-1-thread-1 is working ...
4-pool-1-thread-2 Start Time is:1479808026
Finished thread returns future result: the thread is 2
has been completed
Finished thread returns future result: the thread is 3
Not completed
4-pool-1-thread-2 is working ...
Finished thread returns future result: the thread is 4
-------------
More java,angular,android, large data, J2ee,python, database, Linux,java architects,:
Http://www.cnblogs.com/zengmiaogen/p/7083694.html