executor

package com.threadTest;

import java.util.ArrayList;
import java.util.Date;
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;

//转载于:http://www.cnblogs.com/yezhenhan/archive/2012/01/09/2317636.html
/**
 * 
 * 
 * * @ClassName: TestExecutor
 * 
 * @Description: 
 *               TODO(联系executor,future,ExecutorService,Callable等类在多线程的使用submit,shutdown方法
 *               )
 * @author KXD
 * @date 2016年3月12日 下午9:46:07
 */
public class TestExecutor
{
    public static void main(String[] args) throws InterruptedException,
            ExecutionException
    {
        System.out.println("程序开始运行");
        Date date1 = new Date();
        int taskSize = 5;
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        List<Future> list = new ArrayList<Future>();
        for (int i = 0; i < taskSize; i++)
        {
            Callable c = new MyCallable(i + "");
            Future f = pool.submit(c);
            list.add(f);
        }
        pool.shutdown();
        for (Future f : list)
        {
            System.out.println("<<<<<<" + f.get().toString());
        }

    }
}

class MyCallable implements Callable<Object>
{
    private String taskNum;

    MyCallable(String taskNum)
    {
        this.taskNum = taskNum;
    }

    @Override
    public Object call() throws Exception
    {
        System.out.println(">>>" + taskNum + "任务启动");
        Date dateTmpl = new Date();
        Thread.sleep(1000);
        Date dateTmpl2 = new Date();
        long time = dateTmpl2.getTime() - dateTmpl.getDate();
        System.out.println(">>>" + taskNum + "任务结束");
        return taskNum + "务返回运行结果,当前任务时间【" + time + "毫秒】";
    }

}


你可能感兴趣的:(executor)