龙空技术网

超实用线程池工具类(有返回值)

爱音乐的程序员小新人 501

前言:

而今同学们对“线程返回值”大体比较着重,看官们都想要分析一些“线程返回值”的相关内容。那么小编也在网络上汇集了一些对于“线程返回值””的相关内容,希望你们能喜欢,各位老铁们快快来学习一下吧!

/** * Description: 简约型线程池设计工具 * <p> * 1.获得单例,线程池大小容量为5的线程池, 等待销毁时间0l * 2.一些常用的线程操作 * </p> * User: zhouzhou * Date: 2018-08-23 * Time: 11:22 */public class ThreadPoolUtils { private static ExecutorService threadPool ; /** * 单例获取线程池 * @return 大小5的线程池 */ public static ExecutorService getThreadPool(){ if (threadPool == null) { // 全局锁 synchronized (ThreadPoolUtils.class){ threadPool = Executors.newFixedThreadPool(5); return threadPool; } } else { return threadPool; } } /** * 执行线程操作 * @param callable 线程对象 * @param <T> * @return 对象 * @throws Exception */ public static <T> Future<T> submit(Callable<T> callable) throws Exception{ if (threadPool == null){ getThreadPool(); } return threadPool.submit(callable); } }

实际中如何实用呢?

编写Callable类

class TestCallable implements Callable<String> { private String message; public TestCallable(String message) { this.message = message; } @Override public String call() throws Exception { Thread.sleep(300); System.out.println(String.format("打印消息%s", message)); return "OK"; } }

编写测试方法

@Test public void test() throws Exception{ long start = System.currentTimeMillis(); List<Future> futureList = new ArrayList(); // 发送10次消息 for (int i = 0; i < 10; i++) { try { Future<String> messageFuture = ThreadPoolUtils.submit(new TestCallable(String.format("这是第{%s}条消息", i))); futureList.add(messageFuture); } catch (Exception e) { e.printStackTrace(); } } for (Future<String> message : futureList) { String messageData = message.get(); } System.out.println(String.format("共计耗时{%s}毫秒", System.currentTimeMillis() - start)); }

结果打印: 10条消息耗时原来需要3000毫秒, 现在只需要600+毫秒,因为线程大小是5,所以阻塞时间有300ms的偏差,实际运用中,多线程的线程数,也要管理起来, 具体可以参考我的其他文档.

打印消息这是第{2}条消息打印消息这是第{0}条消息打印消息这是第{4}条消息打印消息这是第{1}条消息打印消息这是第{3}条消息打印消息这是第{8}条消息打印消息这是第{5}条消息打印消息这是第{9}条消息打印消息这是第{6}条消息打印消息这是第{7}条消息共计耗时{661}毫秒

标签: #线程返回值