@xmruibi
2015-03-10T01:09:29.000000Z
字数 1825
阅读 679
concurrency_programing
package main;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;public class ExecutorTest {public static void main(String[] args) {// different executor types:ExecutorService execCached = Executors.newCachedThreadPool();ExecutorService execFixed = Executors.newFixedThreadPool(5);ExecutorService execSingle = Executors.newSingleThreadExecutor();// execute runnable object//for (int i = 0; i < 5; i++)// execCached.execute(new ExecRunObject(5));// execFixed.execute(new ExecRunObject(5));// execSingle.execute(new ExecRunObject(5));//execCached.shutdown();/** The following example is for callable interface implementation **/ExecutorService execCall = Executors.newCachedThreadPool();// exec submit produce Future objectArrayList<Future<String>> res = new ArrayList<Future<String>>();for (int i = 0; i < 5; i++)res.add(execCall.submit(new ExecCallObject(i)));for (Future f : res)try {System.out.println(f.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}finally{execCall.shutdown();}}}// implements runnable interfaceclass ExecRunObject implements Runnable {protected int countDown = 10;private static int taskCount = 0;private final int id = taskCount++;public ExecRunObject(int countDown) {this.countDown = countDown;}public String status() {return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff") + ")";}@Overridepublic void run() {while (countDown-- > 0) {System.out.print(status());Thread.yield();}}}// implements callable interface, in order to acquire return value from tasksclass ExecCallObject implements Callable<String> {private int id;public ExecCallObject(int id) {this.id = id;}@Overridepublic String call() throws Exception {// TODO Auto-generated method stubreturn "result of Task" + id;}}