自定义线程池例子:
public static void main(String[] args) { //定义自己的线程池 ForkJoinPool pool = new ForkJoinPool(10); String str = "my name is fangshixiang"; pool.execute(() -> Stream.of(str.split(" ")).parallel().peek(x -> System.out.println(Thread.currentThread().getName() + "___" + x)) .map(x -> x.length()).count()); pool.shutdown(); //关闭线程池(一般都不需要关的) //下面代码是为了让main线程不要退出,因为如果退出太早,上面不会有东西输出的 //提示一点 wait外面必须有synchronized关键字,因为没有会报错的 synchronized (pool) { try { pool.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } 输出: ForkJoinPool-1-worker-2___name ForkJoinPool-1-worker-13___my ForkJoinPool-1-worker-9___is ForkJoinPool-1-worker-11___fangshixiang
可以明显看出,这里输出的就是我们自己自定义的线程池了,就能很好的保证效率了。
无状态演示:(必须那并行流演示) 因为串行流将没有任何效果,因为是线程安全的
public static void main(String[] args) { //打印每个单词的长度 String str = "my name is fangshixiang good"; Stream.of(str.split(" ")) .parallel() .peek(x -> System.out.println(Thread.currentThread().getName() + "___" + x)) .map(x -> x.length()) //.sorted() .peek(x -> System.out.println(Thread.currentThread().getName() + "___" + x)) .count(); } 输出: ForkJoinPool.commonPool-worker-1___name ForkJoinPool.commonPool-worker-3___good ForkJoinPool.commonPool-worker-1___4 ForkJoinPool.commonPool-worker-1___fangshixiang ForkJoinPool.commonPool-worker-1___12 ForkJoinPool.commonPool-worker-2___my ForkJoinPool.commonPool-worker-2___2 main___is main___2 ForkJoinPool.commonPool-worker-3___4
虽然每次执行的顺序不一样,但是每次main都是处理is和2。再看下面加入sorted
第一次执行: main___good ForkJoinPool.commonPool-worker-1___name ForkJoinPool.commonPool-worker-1___my main___fangshixiang ForkJoinPool.commonPool-worker-1___is main___4 ForkJoinPool.commonPool-worker-3___2 ForkJoinPool.commonPool-worker-2___4 ForkJoinPool.commonPool-worker-1___12 ForkJoinPool.commonPool-worker-3___2 再次执行: main___good ForkJoinPool.commonPool-worker-2___is main___fangshixiang ForkJoinPool.commonPool-worker-1___name ForkJoinPool.commonPool-worker-3___my main___4 ForkJoinPool.commonPool-worker-1___12 main___4 ForkJoinPool.commonPool-worker-2___2 ForkJoinPool.commonPool-worker-3___2
我们会发现每次的结果都不一样,原因就是因为sorted是有状态的,所以有了很多的不确定性。