这是我参与8月更文挑战的第28天,活动详情查看:8月更文挑战
写一段串行代码
public class StreamDemo5 {
public static void main(String[] args) {
IntStream.range(1,100).peek(StreamDemo5::debug).count();
}
public static void debug(int i){
System.out.println("debug"+i);
try {
TimeUnit.SECONDS.sleep(3);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
我们调用一下 parallel()函数,则变成了并行流
IntStream.range(1,100).parallel().peek(StreamDemo5::debug).count();
试一下先并行再串行
调用串行函数 sequential
public static void main(String[] args) {
// IntStream.range(1,100).parallel().peek(StreamDemo5::debug).count();
IntStream.range(1,100).parallel().peek(StreamDemo5::debug)
.sequential().peek(StreamDemo5::debug2)
.count();
}
public static void debug(int i){
System.out.println("debug"+i);
try {
TimeUnit.SECONDS.sleep(3);
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void debug2(int i){
System.err.println("debug"+i);
try {
TimeUnit.SECONDS.sleep(3);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
为了效果 debug2 输出位 err
很显然 失败了,得到结论多次调用parallel,sequential只会以最后一次为准
如何修改并行线程数
这里核心数量为 8,所以并行每次打印8个,
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","5");
IntStream.range(1,100).parallel().peek(StreamDemo5::debug).count();
这里将核心数改为了5
所有的并行流都用一个的话,就可能又阻塞,所以我们应该有个自己的线程池。
//创建自己的线程池,不适用默认线城池,防止任务被阻塞
ForkJoinPool pool = new ForkJoinPool(20);
pool.submit(()->IntStream.range(1,100).parallel().peek(StreamDemo5::debug).count());
pool.shutdown();
}
执行看结果
没有任何输出就退出了
这是因为我们在Main函数测试,主函数退出,我们的线程池默认为守护线程,所以也推出了,这里我们用个最简单的方式解决:让主函数傻等一会
ForkJoinPool pool = new ForkJoinPool(20);
pool.submit(()->IntStream.range(1,100).parallel().peek(StreamDemo5::debug).count());
pool.shutdown();
synchronized (pool){
pool.wait();
}