Executor是JDK5引入的接口,在并发包里,提供了耦合度更低,线程组管理的多线程实现方式,其中ExecutorService接口继承自Executor接口,分别提供了有返回值和无返回值的线程调用:
如若转载,请说明出处! http://blog.csdn.net/xukunddp
public class Example1 {
public static void main(String args[]) {
// For runnable call, traditional thread implementation
Thread runner = new Thread(new Runner());
runner.start();
//Call Executor method execute(), without return value
Executor ex = Executors.newFixedThreadPool(2);
ex.execute(new Runner());
//ExecutorService extends Executor , call ExecutorService method submit() with return value getting from Future interface.
ExecutorService es = Executors.newFixedThreadPool(3);
Future<Integer> f = es.submit(new CallableRunner());
int rtv = 0;
try {
rtv = f.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
es.shutdown();
}
if (rtv == 7) {
System.out.println("Callable call is finished.");
}
}
}
class Runner implements Runnable {
public void run() {
System.out.println("Runner is running.");
}
}
class CallableRunner implements Callable<Integer> {
public Integer call() {
System.out.println("CallableRunner starts to run.");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 7;
}
}
如若转载,请说明出处! http://blog.csdn.net/xukunddp