import java.util.concurrent.*; class FibonacciTask extends RecursiveTask<Integer> { private final int n; public FibonacciTask(int n) { this.n = n; } @Override protected Integer compute() { if (n <= 1) { return n; } else { FibonacciTask f1 = new FibonacciTask(n - 1); f1.fork(); FibonacciTask f2 = new FibonacciTask(n - 2); return f2.compute() + f1.join(); } } } public class ForkJoinExample { public static void main(String[] args) { ForkJoinPool forkJoinPool = new ForkJoinPool(); FibonacciTask task = new FibonacciTask(10); int result = forkJoinPool.invoke(task); System.out.println("Result: " + result); } } import java.util.concurrent.*; public class ParallelArrayExample { public static void main(String[] args) { ForkJoinPool forkJoinPool = new ForkJoinPool(); int[] array = {1, 2, 3, 4, 5}; ParallelArray<Integer> parallelArray = ParallelArray.createFromCopy(array, forkJoinPool); int sum = parallelArray.withMapping(x -> x * 2) .reduce(0, (x, y) -> x + y); System.out.println("Sum: " + sum); } } import java.util.concurrent.*; public class PhaserExample { public static void main(String[] args) { Phaser phaser = new Phaser(); Thread[] threads = new Thread[5]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(() -> { System.out.println("Thread " + Thread.currentThread().getId() + " start"); phaser.arriveAndAwaitAdvance(); System.out.println("Thread " + Thread.currentThread().getId() + " end"); }); threads[i].start(); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }


上一篇:
下一篇:
切换中文