zoukankan      html  css  js  c++  java
  • 线程池submit()使用案例

    submit()使用案例
    public class Test {
    private static final String SUCCESS = "success";

    public static void main(String[] args) {

    ExecutorService executorService = Executors.newFixedThreadPool(3);

    System.out.println("------------------任务开始执行---------------------");

    Future<String> future = executorService.submit(new Callable<String>() {
    @Override
    public String call() throws Exception {
    Thread.sleep(5000);
    System.out.println("submit方法执行任务完成" + " thread name: " + Thread.currentThread().getName());
    return SUCCESS;
    }
    });

    try {
    String s = future.get();
    if (SUCCESS.equals(s)) {
    String name = Thread.currentThread().getName();
    System.out.println("经过返回值比较,submit方法执行任务成功 thread name: " + name);
    }
    } catch (InterruptedException e) {
    e.printStackTrace();
    } catch (ExecutionException e) {
    e.printStackTrace();
    }

    System.out.println("-------------------main thread end---------------------");
    }
    }

    打印结果:

    ------------------任务开始执行---------------------
    call()调用开始: 1496899867882
    submit方法执行任务完成: 1496899872897 thread name: pool-1-thread-1
    经过返回值比较,submit方法执行任务成功 thread name: main
    -------------------main thread end---------------------
    1
    2
    3
    4
    5
    6
    主线程会一直阻塞,等待线程池中的任务执行完后,在执行后面的语句。
     

    团队五人,专业从事软件开发,接单工作,专注于Java,.Net,PHP
  • 相关阅读:
    hdu 4864(2) 线段树
    hdu 4864
    Codeforces Round #256 (Div. 2)
    BestCoder Round #1 1001 && 1002 hdu 4857 4858
    [Groovy]Parse properties file in Groovy
    [Shell]Shell学习笔记之for
    [转]Groovy Goodness
    SoapUI Properties的使用
    [转]Groovy One Liners to Impress Your Friends
    How can I use wget in Windows
  • 原文地址:https://www.cnblogs.com/xiaohouye/p/14647860.html
Copyright © 2011-2022 走看看