Home  >  Q&A  >  body text

java线程为什么这样没有输出

 List<String> list = Arrays.asList("a","b","c","d");
 ExecutorService service = Executors.newFixedThreadPool(2);
 service.execute(() -> list.parallelStream().forEach(System.out::println));

这样一段代码什么都没输出,而将parallelStream去掉就可以输出,这是什么机制?谁能解释下

黄舟黄舟2744 days ago537

reply all(3)I'll reply

  • 阿神

    阿神2017-04-18 10:51:08

    The parallelStream method is executed concurrently, which is equivalent to turning on the thread to output sout.
    The reason why there is no output is that the main thread has finished executing, and the sub-thread has finished. There is no soout at this time. Add a wait at the end of the code and you can see the effect

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:51:08

    parallel...What is this method used for?

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:51:08

    The answer on the second floor is very good
    It is equivalent to opening n+ threads instead of n

    reply
    0
  • Cancelreply