ExecutorService启动线程
1,Java5版本以后,使用ExecutorService启动线程,比之前的版本中的Thread的start()更好
2,创建ExecutorService
ExecutorService es = Executors.newCachedThreadPool();
3,ExecutorService执行任务
任务类型:
实现Runnable接口的类 (无返回值)
实现Callable接口的类 (有返回值)
3-1, 执行(Runnable)任务
(1),无返回值: <T> Future<T> submit(Runnable task)
es.submit(new Thread(){ public void run(){ //实现部分 } });
(2),有返回值: <T> Future<T> submit(Runnable task, T result)
String result = "END"; Future<String> rs = es.submit(new Thread(){ public void run(){ //实现部分 } }, result); String end = ""; try { end = rs.get(); //获取执行结果 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println(end); // 执行结果: END
3-2,执行(Callable)任务
(1)有返回值 : <T> Future<T> submit(Callable<T> task)
String mobile = "13050230361"; Map<String, String> map = new HashMap<String, String>(); Future<String> rs = es.submit(new TaskThread(mobile, map)); String end = ""; try { end = rs.get(); //获取执行结果 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println(end); // 执行结果: OK
任务实现类:
class TaskThread implements Callable<String>{ private String mobile; private Map<String, String> map; public TaskThread(String mobile, Map<String, String> map) { super(); this.mobile = mobile; this.map = map; } @Override public String call() throws Exception { if(mobile == null){ return null; } return "OK"; } }
4,用例:发送短信