首页 > 编程语言 > 详细

使用多线程 执行有返回值的方法

时间:2020-05-28 09:53:14      阅读:37      评论:0      收藏:0      [点我收藏+]
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

使用多线程 执行有返回值的方法

原文:https://www.cnblogs.com/ctaixw/p/12977818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!