newFixedThreadPool线程池的使用

2018-11-20  本文已影响0人  Perfect_0c38

@RestController

public class DemoController {

    public static void main(String[] args) {

        List strs =new ArrayList<>();

        getStrs(strs);

        System.out.println("strs = " + strs);

}

   public static void getStrs(List strs){

          List> list =new ArrayList<>();

          ExecutorService service =null;

          try {

              service = Executors.newFixedThreadPool(5);

              for (int i =0; i <5; i++) {

                  Future future = service.submit(new AbcCallable("a" + i, service.getClass().getName()));

                  list.add(future);

}

            for (Future future : list) {

               try {

                    strs.add(future.get());

                }catch (Exception e) {

                    e.printStackTrace();

        }

    }

}catch (Exception e) {

    e.printStackTrace();

}finally {

    service.shutdown();

    }

    }

}

public class AbcCallableimplements Callable {

    private Stringname;

    private StringthreadName;

    public AbcCallable(String name, String threadName) {

    this.name = name;

    this.threadName = threadName;

}

@Override

    public String call()throws Exception {

    System.out.println("name = " +name +": threadName = " +threadName);

    return name;

    }

}

上一篇 下一篇

猜你喜欢

热点阅读