本文整理汇总了Java中java.util.concurrent.ForkJoinPool类的典型用法代码示例。如果您正苦于以下问题:Java ForkJoinPool类的具体用法?Java ForkJoinPool怎么用?Java ForkJoinPool使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ForkJoinPool类属于java.util.concurrent包,在下文中一共展示了ForkJoinPool类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
int count = 0;
for (int i = 1; i < 10; i++) {
count = count + i;
Thread.sleep(1000);
}
System.out.println(count);
long endTime = System.currentTimeMillis(); // 获取结束时间
System.out.println("程序运行时间: " + (startTime - endTime) + "ms");
long startTime1 = System.currentTimeMillis();
CountTask countTask = new CountTask(1, 10);
ForkJoinPool forkJoinPool = new ForkJoinPool();
Future<Integer> futureTask = forkJoinPool.submit(countTask);
try {
System.out.println(futureTask.get());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime1 = System.currentTimeMillis(); // 获取结束时间
System.out.println("程序运行时间: " + (startTime1 - endTime1) + "ms");
}
示例2: testCreateKeyMultithreaded
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
@Test
public void testCreateKeyMultithreaded() {
final int count = 100000;
final Collection<Callable<String>> tasks = IntStream.range(0, count).boxed()
.map(i -> (Callable<String>) () -> KeyGenerator.createKey()).collect(Collectors.toList());
final ForkJoinPool pool = ForkJoinPool.commonPool();
final List<Future<String>> results = pool.invokeAll(tasks);
final Set<String> keys = results.stream().map(t -> {
try {
return t.get();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}).collect(Collectors.toSet());
Assert.assertEquals("If " + count + " key generations are performed in parallel, it should yield " + count
+ " of distinct keys", count, keys.size());
}
示例3: testExecuteRunnable
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
/**
* execute(runnable) runs it to completion
*/
public void testExecuteRunnable() throws Throwable {
ExecutorService e = new ForkJoinPool(1);
try (PoolCleaner cleaner = cleaner(e)) {
final AtomicBoolean done = new AtomicBoolean(false);
Future<?> future = e.submit(new CheckedRunnable() {
public void realRun() {
done.set(true);
}});
assertNull(future.get());
assertNull(future.get(randomExpiredTimeout(), randomTimeUnit()));
assertTrue(done.get());
assertTrue(future.isDone());
assertFalse(future.isCancelled());
}
}
示例4: GeneratorIterator
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
public GeneratorIterator(int maxWorkQueueDepth, Generator<U> theGenerator, Completion completion,
Consumer<Throwable> exceptionHandler)
{
this.maxWorkQueueDepth = maxWorkQueueDepth;
this.completion = completion;
this.exceptionHandler = exceptionHandler;
this.workQueue = new ArrayBlockingQueue<>(maxWorkQueueDepth);
this.drainedItems = new ArrayList<>(maxWorkQueueDepth + 1);
this.isForkJoinTaskComplete = new AtomicBoolean(false);
this.future = ForkJoinPool.commonPool().submit(() -> {
try {
theGenerator.call(this.workQueue::put);
} catch(InterruptedException ex) {
} finally {
this.workQueue.done();
}
return null; // Void future requires a return value of null
});
this.drainedItemsCount = this.position = maxWorkQueueDepth;
}
示例5: testInvokeOnPool
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
private void testInvokeOnPool(ForkJoinPool pool, RecursiveAction a) {
try (PoolCleaner cleaner = cleaner(pool)) {
assertFalse(a.isDone());
assertFalse(a.isCompletedNormally());
assertFalse(a.isCompletedAbnormally());
assertFalse(a.isCancelled());
assertNull(a.getException());
assertNull(a.getRawResult());
assertNull(pool.invoke(a));
assertTrue(a.isDone());
assertTrue(a.isCompletedNormally());
assertFalse(a.isCompletedAbnormally());
assertFalse(a.isCancelled());
assertNull(a.getException());
assertNull(a.getRawResult());
}
}
示例6: testSetUncaughtExceptionHandler
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
/**
* setUncaughtExceptionHandler changes handler for uncaught exceptions.
*
* Additionally tests: Overriding ForkJoinWorkerThread.onStart
* performs its defined action
*/
public void testSetUncaughtExceptionHandler() throws InterruptedException {
final CountDownLatch uehInvoked = new CountDownLatch(1);
final Thread.UncaughtExceptionHandler ueh =
new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
threadAssertTrue(e instanceof MyError);
threadAssertTrue(t instanceof FailingFJWSubclass);
uehInvoked.countDown();
}};
ForkJoinPool p = new ForkJoinPool(1, new FailingThreadFactory(),
ueh, false);
try (PoolCleaner cleaner = cleaner(p)) {
assertSame(ueh, p.getUncaughtExceptionHandler());
try {
p.execute(new FibTask(8));
await(uehInvoked);
} finally {
p.shutdownNow(); // failure might have prevented processing task
}
}
}
示例7: post
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
final <T> void post(@NotNull Consumer<T> callback, T state, boolean mainThreadAffinitized) {
Requires.notNull(callback, "callback");
if (mainThreadAffinitized) {
JoinableFuture<?> transientFuture = this.runAsync(() -> {
this.getContext().getAmbientFuture().post(callback, state, true);
return Futures.completedNull();
});
if (transientFuture.getFuture().isCompletedExceptionally()) {
// rethrow the exception.
transientFuture.getFuture().join();
}
} else {
ForkJoinPool.commonPool().execute(ExecutionContext.wrap(() -> callback.accept(state)));
}
}
示例8: AbstractJFBSorting
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
AbstractJFBSorting(int maximumPoints, int maximumDimension, int allowedThreads) {
super(maximumPoints, maximumDimension);
if (allowedThreads == 1) {
pool = null; // current thread only execution
} else {
pool = allowedThreads > 1 ? new ForkJoinPool(allowedThreads) : new ForkJoinPool();
}
this.allowedThreads = allowedThreads > 0 ? allowedThreads : -1;
sorter = new DoubleArraySorter(maximumPoints);
medianSwap = new double[maximumPoints];
indices = new int[maximumPoints];
ranks = new int[maximumPoints];
points = new double[maximumPoints][];
transposedPoints = new double[maximumDimension][maximumPoints];
rankQuery = createStructure(maximumPoints);
internalIndices = new int[maximumPoints];
lastFrontOrdinates = new double[maximumPoints];
splitMerge = new SplitMergeHelper(maximumPoints);
}
示例9: testInvokeAll4
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
/**
* get of returned element of invokeAll(c) throws
* ExecutionException on failed task
*/
public void testInvokeAll4() throws Throwable {
ExecutorService e = new ForkJoinPool(1);
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<>();
l.add(new NPETask());
List<Future<String>> futures = e.invokeAll(l);
assertEquals(1, futures.size());
try {
futures.get(0).get();
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
}
}
示例10: realMain
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
private static void realMain(String[] args) throws Throwable {
if (debug) {
String pp = System.getProperty(
"java.util.concurrent.ForkJoinPool.common.parallelism");
System.out.println(
"java.util.concurrent.ForkJoinPool.common.parallelism:" + pp);
String tf = System.getProperty(
"java.util.concurrent.ForkJoinPool.common.threadFactory");
System.out.println(
"java.util.concurrent.ForkJoinPool.common.threadFactory:" + tf);
}
long from = 0, to = 50000;
RecursiveTask<Long> task = new SumTask(from, to, Thread.currentThread());
long sum = task.invoke();
System.out.printf("%nSum: from [%d] to [%d] = [%d]%n", from, to, sum);
task.fork();
sum = task.join();
System.out.printf("%nSum: from [%d] to [%d] = [%d]%n", from, to, sum);
sum = ForkJoinPool.commonPool().invoke(task.fork());
System.out.printf("%nSum: from [%d] to [%d] = [%d]%n", from, to, sum);
}
示例11: demo1_class_level_integration
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
private static void demo1_class_level_integration() {
String result = IntStream.rangeClosed(1, speedLimitByLane.length).mapToDouble(i -> {
AverageSpeed averageSpeed = new AverageSpeed(trafficUnitsNumber, timeSec, dateLocation, speedLimitByLane, i,100);
ForkJoinPool commonPool = ForkJoinPool.commonPool();
return commonPool.invoke(averageSpeed);
}).mapToObj(Double::toString).collect(Collectors.joining(", "));
System.out.println("Average speed = " + result);
TrafficDensity trafficDensity = new TrafficDensity();
Integer[] trafficByLane = trafficDensity.trafficByLane(trafficUnitsNumber, timeSec, dateLocation, speedLimitByLane );
System.out.println("Traffic density = " + Arrays.stream(trafficByLane).map(Object::toString).collect(Collectors.joining(", ")));
}
示例12: blur
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
public static BufferedImage blur(BufferedImage srcImage) {
int w = srcImage.getWidth();
int h = srcImage.getHeight();
int[] src = srcImage.getRGB(0, 0, w, h, null, 0, w);
int[] dst = new int[src.length];
System.out.println("Array size is " + src.length);
System.out.println("Threshold is " + sThreshold);
int processors = Runtime.getRuntime().availableProcessors();
System.out.println(Integer.toString(processors) + " processor"
+ (processors != 1 ? "s are " : " is ")
+ "available");
ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
ForkJoinPool pool = new ForkJoinPool();
long startTime = System.currentTimeMillis();
pool.invoke(fb);
long endTime = System.currentTimeMillis();
System.out.println("Image blur took " + (endTime - startTime) +
" milliseconds.");
BufferedImage dstImage =
new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
dstImage.setRGB(0, 0, w, h, dst, 0, w);
return dstImage;
}
示例13: getAverageMoreProcessors
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
public double getAverageMoreProcessors() throws InterruptedException, ExecutionException{
ToIntFunction<Employee> sizeEmpArr = (e) -> {
System.out.println("Thread: " + Thread.currentThread().getName());
return e.getAge();
};
Callable<Double> task = () -> employeeDaoImpl.getEmployees().stream().mapToInt(sizeEmpArr).average().getAsDouble();
ForkJoinPool forkJoinPool = new ForkJoinPool(4);
double avgAge = forkJoinPool.submit(task).get();
return avgAge;
}
示例14: testAbnormalInvoke
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
public void testAbnormalInvoke(ForkJoinPool pool) {
RecursiveAction a = new CheckedRecursiveAction() {
protected void realCompute() {
FailingAsyncFib f = new FailingAsyncFib(8);
try {
f.invoke();
shouldThrow();
} catch (FJException success) {
checkCompletedAbnormally(f, success);
}
}};
testInvokeOnPool(pool, a);
}
示例15: testTimedInvokeAll1
import java.util.concurrent.ForkJoinPool; //导入依赖的package包/类
/**
* timed invokeAll(null) throws NullPointerException
*/
public void testTimedInvokeAll1() throws Throwable {
ExecutorService e = new ForkJoinPool(1);
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAll(null, randomTimeout(), randomTimeUnit());
shouldThrow();
} catch (NullPointerException success) {}
}
}