}
};
int n = 3;
CyclicAction[] actions = new CyclicAction[n];
for (int i = 0; i < n; ++i) {
final int index = i;
actions[i] = new CyclicAction(b) {
protected void compute() {
System.out.println("I'm working " + getCycle() + " "
+ index);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
for (int i = 0; i < n; ++i)
actions[i].fork();
for (int i = 0; i < n; ++i)
actions[i].join();
}
}
public class TestForkJoin {
@Test
public void testBarrier () throws InterruptedException, ExecutionException {
System.out.println("\ntesting Task Barrier ...");
ForkJoinTask fjt = new ConcurrentPrint();
ForkJoinPool fjpool = new ForkJoinPool(4);
fjpool.submit(fjt);
fjpool.shutdown();
}
@Test
public void testFibonacci () throws InterruptedException, ExecutionException {
System.out.println("\ntesting Fibonacci ...");
final int num = 14; //For demo only
ForkJoinTask<Integer> fjt = new Fibonacci(num);
ForkJoinPool fjpool = new ForkJoinPool();
Future<Integer> result = fjpool.submit(fjt);
// do something
System.out.println("Fibonacci(" + num + ") = " + result.get());
}
}
文章来源于领测软件测试网 https://www.ltesting.net/