一、概述
注意:因为线程池是全局共享的,所以我们尽量不要在 parallelStream 中执行阻塞任务,否则会影响到整个系统中其他的 parallelStream 任务执行的。
二、案例
public static void main(String[] args) {
try {
// 构建list数据 List list = new ArrayList<>(20); for (int i = 0; i < 20; i++) {
list.add(i); } // 启动第一个线程,在里面执行 Thread t_A = new Thread(() -> {
list.parallelStream().forEach((i) -> {
System.out.println(i + "=====A=====" + Thread.currentThread().getName()); try {
Thread.sleep(10000); } catch (InterruptedException e) {
e.printStackTrace(); } }); }); t_A.start(); // 暂停2秒 Thread.sleep(2000); //执行第二个线程 Thread t_B = new Thread(() -> {
list.parallelStream().forEach((i) -> {
System.out.println(i + "=====B=====" + Thread.currentThread().getName()); }); }); t_B.start(); t_A.join(); t_B.join(); } catch (InterruptedException e) {
e.printStackTrace(); } }
12=====A=====Thread-0 6=====A=====ForkJoinPool.commonPool-worker-9 7=====A=====ForkJoinPool.commonPool-worker-6 2=====A=====ForkJoinPool.commonPool-worker-2 8=====A=====ForkJoinPool.commonPool-worker-11 4=====A=====ForkJoinPool.commonPool-worker-4 5=====A=====ForkJoinPool.commonPool-worker-15 1=====A=====ForkJoinPool.commonPool-worker-13 3=====A=====ForkJoinPool.commonPool-worker-8 9=====A=====ForkJoinPool.commonPool-worker-1 0=====A=====ForkJoinPool.commonPool-worker-10 17=====A=====ForkJoinPool.commonPool-worker-3 12=====B=====Thread-1 14=====B=====Thread-1 13=====B=====Thread-1 11=====B=====Thread-1 10=====B=====Thread-1 17=====B=====Thread-1 19=====B=====Thread-1 18=====B=====Thread-1 16=====B=====Thread-1 15=====B=====Thread-1 6=====B=====Thread-1 5=====B=====Thread-1 8=====B=====Thread-1 9=====B=====Thread-1 7=====B=====Thread-1 2=====B=====Thread-1 4=====B=====Thread-1 3=====B=====Thread-1 1=====B=====Thread-1 0=====B=====Thread-1 13=====A=====ForkJoinPool.commonPool-worker-11 18=====A=====ForkJoinPool.commonPool-worker-3 15=====A=====ForkJoinPool.commonPool-worker-9 10=====A=====ForkJoinPool.commonPool-worker-4 19=====A=====ForkJoinPool.commonPool-worker-10 16=====A=====ForkJoinPool.commonPool-worker-1 11=====A=====ForkJoinPool.commonPool-worker-13 14=====A=====ForkJoinPool.commonPool-worker-8
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/229393.html原文链接:https://javaforall.net
