ExecutorService之execute & submit

public interface ExecutorService extends Executorjava

ExecutorService继承自Executor接口app

 

Executor接口只有一个方法execute

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the <tt>Executor</tt> implementation.
     */
    void execute(Runnable command);
}

 

ExecutorService的submit方法

/**
 * Submits a value-returning task for execution and returns a
 * Future representing the pending results of the task. The
 * Future's <tt>get</tt> method will return the task's result upon
 * successful completion.
 */
<T> Future<T> submit(Callable<T> task);

/**
 * Submits a Runnable task for execution and returns a Future
 * representing that task. The Future's <tt>get</tt> method will
 * return the given result upon successful completion.
 */
<T> Future<T> submit(Runnable task, T result);

/**
 * Submits a Runnable task for execution and returns a Future
 * representing that task. The Future's <tt>get</tt> method will
 * return <tt>null</tt> upon <em>successful</em> completion.
 */
Future<?> submit(Runnable task);

 

ExecutorService的execute方法

/**
 * Executes the given command at some time in the future.  The command
 * may execute in a new thread, in a pooled thread, or in the calling
 * thread, at the discretion of the <tt>Executor</tt> implementation.
 */
void execute(Runnable command);

 

在使用上的区别

import java.util.ArrayList;
import java.util.List;
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 TestExecutorService {

    public static void main(String args[]) {

        List<String> data = new ArrayList<String>();

        for (int i = 0; i < 1034; i++) {
            String str = String.valueOf(i);
            data.add(str);
        }

        int size = data.size();
        int threadNum = 10;

        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);

        List<Future<String>> futures = new ArrayList<Future<String>>();

        for (int i = 0; i < threadNum; i++) {
            int fromIndex = 100 * i;
            int toIndex = 100 * (i + 1);
            if (i == threadNum - 1) {
                toIndex = size;
            }
            final List<String> subList = data.subList(fromIndex, toIndex);

            Callable<String> task = new Callable<String>() {
                @Override
                public String call() throws Exception {
                    StringBuffer sb = new StringBuffer();
                    for (String str : subList) {
                        sb.append(str + ",");
                    }
                    return sb.toString();
                }
            };

            Future<String> taskResult = executorService.submit(task);

            futures.add(taskResult);
        }

        long a = System.currentTimeMillis();

        //shutdown() 方法在终止前容许执行之前提交的任务
        //第一阶段调用 shutdown 拒绝传入任务,而后调用 shutdownNow(若有必要)取消全部遗留的任务
        //提交的任务运行结束后关闭线程池
        executorService.shutdown();

        while (true) {
            /**
             * 经过不断运行ExecutorService.isTerminated()方法检测所有的线程是否都已经运行结束
             */
            if (executorService.isTerminated()) {
                System.out.println("全部任务执行完毕");
                System.out.println("时间差=" + String.valueOf(System.currentTimeMillis() - a));
                break;
            }
            try {
                //milliseconds
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        StringBuffer result = new StringBuffer();

        for (Future<String> future : futures) {
            try {
                /**
                 *  V get() throws InterruptedException, ExecutionException;
                 *  会抛出异常,能够捕获异常,当发生异常时,能够选择当即shutdown其余任务
                 */
                System.out.println("本次任务的执行结果:" + future.get());
                result.append(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                //当即shutdown其余任务
                executorService.shutdownNow();
                e.printStackTrace();
            }
        }

        System.out.println("最终结果:" + result.toString());
    }

}

ExecutorService之execute方法没有返回结果,也不会经过处理结果返回异常。ide

这里有execute方法的使用示例,经过实现Runnable接口定义了一个Task类,实现run方法spa

http://my.oschina.net/xinxingegeya/blog/263276.net

=============END=============线程

相关文章
相关标签/搜索