當前位置: 首頁>>代碼示例>>Java>>正文


Java ForkJoinPool類代碼示例

本文整理匯總了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");

}
 
開發者ID:leon66666,項目名稱:JavaCommon,代碼行數:26,代碼來源:ForkJoinTaskDemo.java

示例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());
}
 
開發者ID:syndesisio,項目名稱:syndesis,代碼行數:23,代碼來源:KeyGeneratorTest.java

示例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());
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:ForkJoinPoolTest.java

示例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;
}
 
開發者ID:roger-dv,項目名稱:spartan-jasync,代碼行數:21,代碼來源:GeneratorIterator.java

示例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());
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:ForkJoinTask8Test.java

示例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
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:28,代碼來源:ForkJoinPoolTest.java

示例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)));
	}
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:18,代碼來源:JoinableFutureFactory.java

示例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);
}
 
開發者ID:mbuzdalov,項目名稱:non-dominated-sorting,代碼行數:23,代碼來源:AbstractJFBSorting.java

示例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);
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:ForkJoinPoolTest.java

示例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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:ThreadLessCommon.java

示例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(", ")));
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Cookbook,代碼行數:13,代碼來源:Chapter15Testing.java

示例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;
}
 
開發者ID:chaokunyang,項目名稱:jkes,代碼行數:33,代碼來源:ForkBlur.java

示例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;
	
}
 
開發者ID:PacktPublishing,項目名稱:Spring-5.0-Cookbook,代碼行數:13,代碼來源:EmployeeParallelStreamService.java

示例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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:14,代碼來源:ForkJoinTask8Test.java

示例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) {}
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:13,代碼來源:ForkJoinPoolTest.java


注:本文中的java.util.concurrent.ForkJoinPool類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。