CallableTest 实例
Runnable是执行工作的独立任务,不返回任何值。
Callable是一中具有类型参数的泛型,run方法对应call方法,通过ExecutorService.submit方法调用
package threadTest;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executors = Executors.newCachedThreadPool();
Future<String> future;
for(int i=0; i<5 ; i++){
future= executors.submit(new CallableImpl(Integer.toString(i)));
System.out.println(future.get());
}
executors.shutdown();
}
}
class CallableImpl implements java.util.concurrent.Callable<String>{
private String callableName;
public CallableImpl(String callableName) {
this.callableName = callableName;
}
@Override
public String call() throws Exception {
return "当前Callable名为: "+callableName;
}
}