在java并发中提供了Callable的一个接口,可以在线程中返回一个参数,这是接口Runable所做不到的。。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableTest {
/**
* 可以返回一个参数
* @author Administrator
*
*/
class TaskCallable implements Callable {
int id;
TaskCallable(int id) {
this.id = id;
}
/**
* 线程中可以返回一个参数
*/
@Override
public String call() throws Exception {
return "xxxx" + id;
}
}
public static void main(String[] args) {
CallableTest test = new CallableTest();
ArrayList> arrFuture = new ArrayList>();//利用future储存
ExecutorService executorServer = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 10; i++) {
Future future = executorServer
.submit(test.new TaskCallable(i));//submit产生futrue对象
arrFuture.add(future);
}
for (Future future : arrFuture) {
System.out.println(future.get());
}
} catch (InterruptedException e) {
System.out.print(e);
} catch (ExecutionException e) {
System.out.print(e);
} finally {
executorServer.shutdown();
}
}
}
call函数返回一个参数,跟Runable所不同的是Runable是调用excute(Thread),Callable是调用
submit(Thread).