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;import org.apache.commons.lang3.RandomStringUtils;
/*** 使用线程池和单线程**/public class TestTask { public static void main(String[] args) throws InterruptedException { long currentTimeMillis = System.currentTimeMillis(); System.out.println("currentTimeMillis:" + currentTimeMillis); useThreadPool(); System.out.println("cost:" + (System.currentTimeMillis() - currentTimeMillis)); System.out.println("==================================================="); currentTimeMillis = System.currentTimeMillis(); useSinglePool(); System.out.println("cost:" + (System.currentTimeMillis() - currentTimeMillis)); } /** * */ private static void useSinglePool() { for (int i = 0; i < 10; i++) { doTask(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(5)); } } /** * */ private static void useThreadPool() { ExecutorService es = Executors.newFixedThreadPool(10); List> list = new ArrayList >(); for (int i = 0; i < 10; i++) { Future future = es.submit(new Callable () { @Override public Boolean call() { return doTask(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(5)); } }); list.add(future); } //关闭线程池,等旧任务执行完,并停止接收新任务 es.shutdown(); try { //获取处理结果 for (Future future : list) { System.out.println(future.get()); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public static boolean doTask(String arg1, String arg2) { System.out.println(Thread.currentThread() + ":" + arg1 + "_" + arg2); try { //模拟业务处理时长 Thread.sleep(1000); return true; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }}
currentTimeMillis:1481104024029Thread[pool-1-thread-2,5,main]:yaJSUdkD4f_v3rqWThread[pool-1-thread-3,5,main]:PpQbrtr7wP_KE78zThread[pool-1-thread-10,5,main]:LSODdw5Zqk_4LxLYThread[pool-1-thread-7,5,main]:KDseIk6FJ9_84qraThread[pool-1-thread-6,5,main]:ucm8VSevwB_WVOhSThread[pool-1-thread-4,5,main]:c132FVrokB_gtQDtThread[pool-1-thread-9,5,main]:KKcWv3rmVc_GR9LZThread[pool-1-thread-5,5,main]:clXJOjW6F4_TlEzfThread[pool-1-thread-8,5,main]:aQBLjR4BTG_KwqBGThread[pool-1-thread-1,5,main]:jtyxUhMTSa_ykpVutruetruetruetruetruetruetruetruetruetruecost:1163===================================================Thread[main,5,main]:ncJJsfIfDH_pu7mjThread[main,5,main]:cFTiqRR8SZ_kXgYzThread[main,5,main]:k27V4Xzs43_9x7iCThread[main,5,main]:Butab2DJHb_4ePjgThread[main,5,main]:qhGBE1iyBE_SHOGjThread[main,5,main]:DEhiau4dqG_fxNa0Thread[main,5,main]:byTFoqVkBC_Lb7vmThread[main,5,main]:Q544NhN0Lr_rpbwSThread[main,5,main]:5nNdV1G1nQ_VkvAKThread[main,5,main]:N3j4o8INfl_eLruRcost:10001