使用多线程 执行有返回值的方法
public class ThreadTest {
private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(50000);
public static ThreadPoolExecutor executor;
static {
executor = new ThreadPoolExecutor(15, 100, 60L,
TimeUnit.SECONDS, queue, new ThreadPoolExecutor.AbortPolicy());
}
public static void main(String[] args) {
List<Future> futureList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int a = i;
Future futureString = executor.submit((Callable<Object>)() -> handle(a));
futureList.add(futureString);
}
int sum = 0;
for (Future future : futureList) {
Integer returnint = (Integer)getFutureObject(future);
System.out.println(returnint +" " + new Date());
sum = sum + returnint;
}
System.out.println(sum);
}
public static int handle(int num) {
int sleepNUM = 10 - num;
System.out.println("num strart " + num +" "+ new Date());
try {
Thread.sleep(sleepNUM * 1000);
}catch (Exception e){}
System.out.println("num end " + num +" " + new Date() );
return num;
}
private static Object getFutureObject(Future future){
try {
return future.get(600, TimeUnit.SECONDS);
}catch (Exception ex){
}
return null;
}
}
---------------------------
num strart 3 Thu May 28 01:55:02 CST 2020
num strart 6 Thu May 28 01:55:02 CST 2020
num strart 1 Thu May 28 01:55:02 CST 2020
num strart 8 Thu May 28 01:55:02 CST 2020
num strart 4 Thu May 28 01:55:02 CST 2020
num strart 0 Thu May 28 01:55:02 CST 2020
num strart 2 Thu May 28 01:55:02 CST 2020
num strart 5 Thu May 28 01:55:02 CST 2020
num strart 7 Thu May 28 01:55:02 CST 2020
num strart 9 Thu May 28 01:55:02 CST 2020
num end 9 Thu May 28 01:55:03 CST 2020
num end 8 Thu May 28 01:55:04 CST 2020
num end 7 Thu May 28 01:55:05 CST 2020
num end 6 Thu May 28 01:55:06 CST 2020
num end 5 Thu May 28 01:55:07 CST 2020
num end 4 Thu May 28 01:55:08 CST 2020
num end 3 Thu May 28 01:55:09 CST 2020
num end 2 Thu May 28 01:55:10 CST 2020
num end 1 Thu May 28 01:55:11 CST 2020
num end 0 Thu May 28 01:55:12 CST 2020
0 Thu May 28 01:55:12 CST 2020
1 Thu May 28 01:55:12 CST 2020
2 Thu May 28 01:55:12 CST 2020
3 Thu May 28 01:55:12 CST 2020
4 Thu May 28 01:55:12 CST 2020
5 Thu May 28 01:55:12 CST 2020
6 Thu May 28 01:55:12 CST 2020
7 Thu May 28 01:55:12 CST 2020
8 Thu May 28 01:55:12 CST 2020
9 Thu May 28 01:55:12 CST 2020
45