标签:udk util hog mem str rand long ice public
/** * 使用线程池和单线程 **/ 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<Future<Boolean>> list = new ArrayList<Future<Boolean>>(); for (int i = 0; i < 10; i++) { Future<Boolean> future = es.submit(new Callable<Boolean>() { @Override public Boolean call() { return doTask(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(5)); } }); list.add(future); }
//关闭线程池,等旧任务执行完,并停止接收新任务 es.shutdown(); try {
//获取处理结果 for (Future<Boolean> 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:1481104024029 Thread[pool-1-thread-2,5,main]:yaJSUdkD4f_v3rqW Thread[pool-1-thread-3,5,main]:PpQbrtr7wP_KE78z Thread[pool-1-thread-10,5,main]:LSODdw5Zqk_4LxLY Thread[pool-1-thread-7,5,main]:KDseIk6FJ9_84qra Thread[pool-1-thread-6,5,main]:ucm8VSevwB_WVOhS Thread[pool-1-thread-4,5,main]:c132FVrokB_gtQDt Thread[pool-1-thread-9,5,main]:KKcWv3rmVc_GR9LZ Thread[pool-1-thread-5,5,main]:clXJOjW6F4_TlEzf Thread[pool-1-thread-8,5,main]:aQBLjR4BTG_KwqBG Thread[pool-1-thread-1,5,main]:jtyxUhMTSa_ykpVu true true true true true true true true true true cost:1163 =================================================== Thread[main,5,main]:ncJJsfIfDH_pu7mj Thread[main,5,main]:cFTiqRR8SZ_kXgYz Thread[main,5,main]:k27V4Xzs43_9x7iC Thread[main,5,main]:Butab2DJHb_4ePjg Thread[main,5,main]:qhGBE1iyBE_SHOGj Thread[main,5,main]:DEhiau4dqG_fxNa0 Thread[main,5,main]:byTFoqVkBC_Lb7vm Thread[main,5,main]:Q544NhN0Lr_rpbwS Thread[main,5,main]:5nNdV1G1nQ_VkvAK Thread[main,5,main]:N3j4o8INfl_eLruR cost:10001
标签:udk util hog mem str rand long ice public
原文地址:http://www.cnblogs.com/ex-yfcai/p/6142266.html