/**
* CallableAndFuture.java
* cn.com.songjy.test.socket.thread
* Function: TODO
*
* version date author
* ──────────────────────────────────
* 1.0 2013-8-17 songjy
*
* Copyright (c) 2013, TNT All Rights Reserved.
*/
package cn.com.songjy.test.socket.thread;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* ClassName:CallableAndFuture
* Callable与Future的应用
* @author songjy
* @version 1.0
* @since v1.0
* @Date 2013-8-17 下午9:13:55
*/
public class CallableAndFuture {
private static Log log = LogFactory.getLog(CallableAndFuture.class);
public static void main(String[] args) {
ExecutorService thread_pools01 = Executors.newSingleThreadExecutor();
Future<String> future = thread_pools01.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5 * 1000l);
return "hello";
}
});
log.info("等待结果...");
try {
// log.info("得到结果:"+future.get());//一直等待执行结果
log.info("得到结果:" + future.get(2, TimeUnit.SECONDS));// 等待2秒,2秒内若未获取到结果则终止任务
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
} catch (ExecutionException e) {
log.error(e.getMessage(), e);
} catch (TimeoutException e) {
log.error(e.getMessage(), e);
}
thread_pools01.shutdown();
ExecutorService thread_pools02 = Executors.newFixedThreadPool(10);// 固定大小线程池
CompletionService<Integer> completion = new ExecutorCompletionService<Integer>(
thread_pools02);
//添加10个任务
for (int i = 0; i < 10; i++) {
final int seq = i;
completion.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
});
}
//获取10个任务执行结果
for(int i=0; i<10; i++) {
try {
log.info(completion.take().get());//哪个任务先执行完则打印哪个的结果
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
} catch (ExecutionException e) {
log.error(e.getMessage(), e);
}
}
thread_pools02.shutdown();
}
}
来自:[url]http://down.51cto.com/data/443429[/url]
public void 线程池() throws InterruptedException, ExecutionException {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
List<Future<Integer>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
int i = new Random().nextInt(100);
System.out.println(i);
return i;
}
});
list.add(future);
}
int sum = 0;
for (Future<Integer> f : list) {
sum += f.get();
}
System.out.println(sum);
}