package demo; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ExecutorDemo { public static void main(String[] args) { //创建线程池 ExecutorService es = Executors.newFixedThreadPool(2); //ExecutorService传入runable来运行 // es.submit(new MyRunable()); // es.shutdown(); //ExecutorService传入callable来运行,可以处理异常、返回结果。 try { Future<String> retStr = es.submit(new MyCallable()); System.out.println(retStr.get()); } catch (Exception e) { e.printStackTrace(); }finally { es.shutdown(); } } } class MyCallable implements Callable<String>{ @Override public String call() throws Exception { return Thread.currentThread().getName()+":正在运行"; } } class MyRunable implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName() + ": 正在运行。"); } }
练习:
通过线程池中的线程对象,使用Callable接口完成两个数求和操作
package demo; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test2 { /* * 要求:通过线程池中的线程对象,使用Callable接口完成两个数求和操作 */ public static void main(String[] args) throws Exception { ExecutorService es = Executors.newFixedThreadPool(2); Future<Integer> retInt = es.submit(new ICallable(1,2)); System.out.println("Sum is : " + retInt.get()); } } class ICallable implements Callable<Integer>{ int x; int y; public ICallable() { super(); } public ICallable(int x, int y) { super(); this.x = x; this.y = y; } @Override public Integer call() throws Exception { return x+y; } }