1. Runnable和Callable
Runnalbe是执行工作的独立任务,但是它不返回任何值。
Callable是一种具有类型参数的泛型,它的类型参数表示的实从方法call()中返回的值,而且必须使用ExecutorService.submit()方法调用它,在Java SE5中引入。
例子:
package
c21;
import
java.util.ArrayList;
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;
class
TaskWithResult
implements
Callable<String>{
private
int
id
;
public
TaskWithResult(
int
id){
this
.
id
= id;
}
public
String call()
throws
Exception {
return
"result of TaskWithResul "
+
id
;
}
}
public
class
CallableDemo {
public
static
void
main(String[] args) {
ExecutorService exec = Executors. newCachedThreadPool();
ArrayList<Future<String>> results =
new
ArrayList<Future<String>>();
for
(
int
i=0;i<10;i++){
results.add(exec.submit(
new
TaskWithResult(i)));
}
for
(Future<String> fs : results){
try
{
System.
out
.println(fs.get());
}
catch
(InterruptedException e) {
System.
out
.println(e);
}
catch
(ExecutionException e) {
System.
out
.println(e);
}
finally
{
exec.shutdown();
}
}
}
}
/**
*
运行结果
result
of
TaskWithResul
0
result
of
TaskWithResul
1
result
of
TaskWithResul
2
result
of
TaskWithResul
3
result
of
TaskWithResul
4
result
of
TaskWithResul
5
result
of
TaskWithResul
6
result
of
TaskWithResul
7
result
of
TaskWithResul
8
result
of
TaskWithResul
9
*/
submit()方法会产生Future对象,它用Callable返回结果的特定类型进行参数化。
用isdone()判断任务是否执行完成。