当前位置: 首页>>代码示例>>Java>>正文


Java ForkJoinPool.execute方法代码示例

本文整理汇总了Java中java.util.concurrent.ForkJoinPool.execute方法的典型用法代码示例。如果您正苦于以下问题:Java ForkJoinPool.execute方法的具体用法?Java ForkJoinPool.execute怎么用?Java ForkJoinPool.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.ForkJoinPool的用法示例。


在下文中一共展示了ForkJoinPool.execute方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: execute

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
public void execute()
{
    finished = new CountDownLatch(Width * Height);

    ForkJoinPool pool = new ForkJoinPool(
            nThreads,
            ForkJoinPool.defaultForkJoinWorkerThreadFactory,
            (t,e) -> e.printStackTrace(),
            false);

    for (Cell cell : cells) {
        pool.execute(cell.neighbors[0]);
    }

    try {
        finished.await();
    }
    catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    pool.shutdown();
}
 
开发者ID:OlegMazurov,项目名称:Koyaanisqatsi,代码行数:23,代码来源:NoWaitLife.java

示例2: 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

示例3: demo2_ForkJoin_execute_join

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
private static void demo2_ForkJoin_execute_join() {
    System.out.println();

    AverageSpeed averageSpeed = createTask();

    ForkJoinPool commonPool = ForkJoinPool.commonPool();
    commonPool.execute(averageSpeed);
    double result = averageSpeed.join();

    System.out.println("result = " + result);
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Cookbook,代码行数:12,代码来源:Chapter07Concurrency04.java

示例4: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * Main method of the example
 * @param args
 */
public static void main(String[] args) {

	// Generate an array of 1000 integers
	ArrayGenerator generator=new ArrayGenerator();
	int array[]=generator.generateArray(1000);
	
	// Create a TaskManager object
	TaskManager manager=new TaskManager();
	
	// Create a ForkJoinPool with the default constructor
	ForkJoinPool pool=new ForkJoinPool();
	
	// Create a Task to process the array
	SearchNumberTask task=new SearchNumberTask(array,0,1000,5,manager);
	
	// Execute the task
	pool.execute(task);

	// Shutdown the pool
	pool.shutdown();
	
	
	// Wait for the finalization of the task
	try {
		pool.awaitTermination(1, TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	// Write a message to indicate the end of the program
	System.out.printf("Main: The program has finished\n");
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:37,代码来源:Main.java

示例5: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * Main method of the class
 */
public static void main(String[] args) {
	// Array of 100 integers
	int array[]=new int[100];
	// Task to process the array
	Task task=new Task(array,0,100);
	// ForkJoinPool to execute the Task
	ForkJoinPool pool=new ForkJoinPool();
	
	// Execute the task
	pool.execute(task);

	// Shutdown the ForkJoinPool
	pool.shutdown();
	
	// Wait for the finalization of the task
	try {
		pool.awaitTermination(1, TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	// Check if the task has thrown an Exception. If it's the case, write it
	// to the console
	
	if (task.isCompletedAbnormally()) {
		System.out.printf("Main: An exception has ocurred\n");
		System.out.printf("Main: %s\n",task.getException());
	}
	
	System.out.printf("Main: Result: %d",task.join());
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:35,代码来源:Main.java

示例6: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * Main method of the example
 * @param args
 */
public static void main(String[] args) {

	// Creates a task
	OneSecondLongTask task=new OneSecondLongTask();
	
	// Creates a new Handler
	Handler handler = new Handler();
	// Creates a Factory
	AlwaysThrowsExceptionWorkerThreadFactory factory=new AlwaysThrowsExceptionWorkerThreadFactory();
	// Creates a new ForkJoinPool
	ForkJoinPool pool=new ForkJoinPool(2,factory,handler,false);
	
	// Execute the task in the pool
	pool.execute(task);

	// Shutdown the pool
	pool.shutdown();
	
	// Wait for the finalization of the tasks
	try {
		pool.awaitTermination(1, TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	System.out.printf("Main: The program has finished.\n");
	
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:33,代码来源:Main.java

示例7: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
public static void main(String[] args) throws Throwable {
    final ForkJoinPool e = new ForkJoinPool(1);
    final AtomicBoolean b = new AtomicBoolean();
    final Runnable setFalse = () -> b.set(false);
    for (int i = 0; i < 100000; i++) {
        b.set(true);
        e.execute(setFalse);
        long st = System.nanoTime();
        while (b.get()) {
            if (System.nanoTime() - st >= TimeUnit.SECONDS.toNanos(10)) {
                throw new RuntimeException("Submitted task failed to execute");
            }
        }
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:16,代码来源:SubmissionTest.java

示例8: testPollSubmission

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * pollSubmission returns unexecuted submitted task, if present
 */
public void testPollSubmission() {
    final CountDownLatch done = new CountDownLatch(1);
    final ForkJoinTask a = ForkJoinTask.adapt(awaiter(done));
    final ForkJoinTask b = ForkJoinTask.adapt(awaiter(done));
    final ForkJoinTask c = ForkJoinTask.adapt(awaiter(done));
    final ForkJoinPool p = singletonPool();
    try (PoolCleaner cleaner = cleaner(p, done)) {
        Thread external = new Thread(new CheckedRunnable() {
            public void realRun() {
                p.execute(a);
                p.execute(b);
                p.execute(c);
            }});
        RecursiveAction s = new CheckedRecursiveAction() {
            protected void realCompute() {
                external.start();
                try {
                    external.join();
                } catch (Exception ex) {
                    threadUnexpectedException(ex);
                }
                assertTrue(p.hasQueuedSubmissions());
                assertTrue(Thread.currentThread() instanceof ForkJoinWorkerThread);
                ForkJoinTask r = ForkJoinTask.pollSubmission();
                assertTrue(r == a || r == b || r == c);
                assertFalse(r.isDone());
            }};
        p.invoke(s);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:34,代码来源:ForkJoinTask8Test.java

示例9: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * @param args
 */
public static void main(String[] args) throws Exception {

	/*
	 * Create the Fork/Join pool
	 */
	ForkJoinPool pool=new ForkJoinPool();
	
	/*
	 * Create a new Array of integer numbers with 10000 elements
	 */
	int array[]=new int[10000];
	
	/*
	 * Create a new task
	 */
	Task task1=new Task(array,0,array.length);
	
	/*
	 * Execute the task in the Fork/Join pool
	 */
	pool.execute(task1);
	
	/*
	 * Wait for the finalization of the task writing information
	 * about the pool every second
	 */
	while (!task1.isDone()) {
		showLog(pool);
		TimeUnit.SECONDS.sleep(1);
	}
	
	/*
	 * Shutdown the pool
	 */
	pool.shutdown();
	
	/*
	 * Wait for the finalization of the pool
	 */
	pool.awaitTermination(1, TimeUnit.DAYS);
	
	/*
	 * End of the program
	 */
	showLog(pool);
	System.out.printf("Main: End of the program.\n");

}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:52,代码来源:Main.java

示例10: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * @param args
 */
public static void main(String[] args) throws Exception {

	/*
	 * Create a new MyWorkerThreadFactory
	 */
	MyWorkerThreadFactory factory=new MyWorkerThreadFactory();
	
	/*
	 * Create new ForkJoinPool, passing as parameter the factory created before
	 */
	ForkJoinPool pool=new ForkJoinPool(4, factory, null, false);
	
	/*
	 * Create and initializes the elements of the array
	 */
	int array[]=new int[100000];
	
	for (int i=0; i<array.length; i++){
		array[i]=1;
	}
	
	/*
	 * Create a new Task to sum the elements of the array
	 */
	MyRecursiveTask task=new MyRecursiveTask(array,0,array.length);
	
	/*
	 * Send the task to the ForkJoinPool 
	 */
	pool.execute(task);
	
	
	/*
	 * Wait for the finalization of the task
	 */
	task.join();
	
	/*
	 * Shutdown the pool
	 */
	pool.shutdown();
	
	/*
	 * Wait for the finalization of the pool
	 */
	pool.awaitTermination(1, TimeUnit.DAYS);
	
	/*
	 * Write the result of the task
	 */
	System.out.printf("Main: Result: %d\n",task.get());
	
	/*
	 * Write a message indicating the end of the program
	 */
	System.out.printf("Main: End of the program\n");
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:61,代码来源:Main.java

示例11: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * Main method of the example
 * @param args
 */
public static void main(String[] args) {

	// Create a list of products
	ProductListGenerator generator=new ProductListGenerator();
	List<Product> products=generator.generate(10000);
	
	// Craete a task
	Task task=new Task(products, 0, products.size(), 0.20);
	
	// Create a ForkJoinPool
	ForkJoinPool pool=new ForkJoinPool();
	
	// Execute the Task
	pool.execute(task);

	// Write information about the pool
	do {
		System.out.printf("******************************************\n");
		System.out.printf("Main: Parallelism: %d\n",pool.getParallelism());
		System.out.printf("Main: Active Threads: %d\n",pool.getActiveThreadCount());
		System.out.printf("Main: Task Count: %d\n",pool.getQueuedTaskCount());
		System.out.printf("Main: Steal Count: %d\n",pool.getStealCount());
		System.out.printf("******************************************\n");
		try {
			TimeUnit.MILLISECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	} while (!task.isDone());

	// Shutdown the pool
	pool.shutdown();
	
	// Check if the task has completed normally
	if (task.isCompletedNormally()){
		System.out.printf("Main: The process has completed normally.\n");
	}

	// Expected result: 12. Write products which price is not 12
	for (int i=0; i<products.size(); i++){
		Product product=products.get(i);
		if (product.getPrice()!=12) {
			System.out.printf("Product %s: %f\n",product.getName(),product.getPrice());
		}
	}
	
	// End of the program
	System.out.println("Main: End of the program.\n");

}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:55,代码来源:Main.java

示例12: main

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * Main method of the example
*/
public static void main(String[] args) {
	// Create the pool
	ForkJoinPool pool=new ForkJoinPool();
	
	// Create three FolderProcessor tasks for three diferent folders
	FolderProcessor system=new FolderProcessor("C:\\Windows", "log");
	FolderProcessor apps=new FolderProcessor("C:\\Program Files","log");
	FolderProcessor documents=new FolderProcessor("C:\\Documents And Settings","log");
	
	// Execute the three tasks in the pool
	pool.execute(system);
	pool.execute(apps);
	pool.execute(documents);
	
	// Write statistics of the pool until the three tasks end
	do {
		System.out.printf("******************************************\n");
		System.out.printf("Main: Parallelism: %d\n",pool.getParallelism());
		System.out.printf("Main: Active Threads: %d\n",pool.getActiveThreadCount());
		System.out.printf("Main: Task Count: %d\n",pool.getQueuedTaskCount());
		System.out.printf("Main: Steal Count: %d\n",pool.getStealCount());
		System.out.printf("Main: %b - %b - %b\n",system.isDone(), apps.isDone(), documents.isDone());
		System.out.printf("Main: %d - %d - %d\n",system.getPendingCount(), apps.getPendingCount(), documents.getPendingCount());
		System.out.printf("******************************************\n");
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	} while ((!system.isDone())||(!apps.isDone())||(!documents.isDone()));
	
	// Shutdown the pool
	pool.shutdown();
	
	// Write the number of results calculate by each task
	List<String> results;
	
	results=system.getResultList();
	System.out.printf("System: %d files found.\n",results.size());
	
	results=apps.getResultList();
	System.out.printf("Apps: %d files found.\n",results.size());
	
	results=documents.getResultList();
	System.out.printf("Documents: %d files found.\n",results.size());
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Concurrency-Cookbook-Second-Edition,代码行数:50,代码来源:Main.java

示例13: testAwaitQuiescence1

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * awaitQuiescence by a worker is equivalent in effect to
 * ForkJoinTask.helpQuiesce()
 */
public void testAwaitQuiescence1() throws Exception {
    final ForkJoinPool p = new ForkJoinPool();
    try (PoolCleaner cleaner = cleaner(p)) {
        final long startTime = System.nanoTime();
        assertTrue(p.isQuiescent());
        ForkJoinTask a = new CheckedRecursiveAction() {
            protected void realCompute() {
                FibAction f = new FibAction(8);
                assertSame(f, f.fork());
                assertSame(p, ForkJoinTask.getPool());
                boolean quiescent = p.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS);
                assertTrue(quiescent);
                assertFalse(p.isQuiescent());
                while (!f.isDone()) {
                    assertFalse(p.getAsyncMode());
                    assertFalse(p.isShutdown());
                    assertFalse(p.isTerminating());
                    assertFalse(p.isTerminated());
                    Thread.yield();
                }
                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
                assertFalse(p.isQuiescent());
                assertEquals(0, ForkJoinTask.getQueuedTaskCount());
                assertEquals(21, f.result);
            }};
        p.execute(a);
        while (!a.isDone() || !p.isQuiescent()) {
            assertFalse(p.getAsyncMode());
            assertFalse(p.isShutdown());
            assertFalse(p.isTerminating());
            assertFalse(p.isTerminated());
            Thread.yield();
        }
        assertEquals(0, p.getQueuedTaskCount());
        assertFalse(p.getAsyncMode());
        assertEquals(0, p.getQueuedSubmissionCount());
        assertFalse(p.hasQueuedSubmissions());
        while (p.getActiveThreadCount() != 0
               && millisElapsedSince(startTime) < LONG_DELAY_MS)
            Thread.yield();
        assertFalse(p.isShutdown());
        assertFalse(p.isTerminating());
        assertFalse(p.isTerminated());
        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:51,代码来源:ForkJoinPool8Test.java

示例14: testAwaitQuiescence2

import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
 * awaitQuiescence returns when pool isQuiescent() or the indicated
 * timeout elapsed
 */
public void testAwaitQuiescence2() throws Exception {
    /**
     * """It is possible to disable or limit the use of threads in the
     * common pool by setting the parallelism property to zero. However
     * doing so may cause unjoined tasks to never be executed."""
     */
    if ("0".equals(System.getProperty(
         "java.util.concurrent.ForkJoinPool.common.parallelism")))
        return;
    final ForkJoinPool p = new ForkJoinPool();
    try (PoolCleaner cleaner = cleaner(p)) {
        assertTrue(p.isQuiescent());
        final long startTime = System.nanoTime();
        ForkJoinTask a = new CheckedRecursiveAction() {
            protected void realCompute() {
                FibAction f = new FibAction(8);
                assertSame(f, f.fork());
                while (!f.isDone()
                       && millisElapsedSince(startTime) < LONG_DELAY_MS) {
                    assertFalse(p.getAsyncMode());
                    assertFalse(p.isShutdown());
                    assertFalse(p.isTerminating());
                    assertFalse(p.isTerminated());
                    Thread.yield();
                }
                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
                assertEquals(0, ForkJoinTask.getQueuedTaskCount());
                assertEquals(21, f.result);
            }};
        p.execute(a);
        assertTrue(p.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(p.isQuiescent());
        assertTrue(a.isDone());
        assertEquals(0, p.getQueuedTaskCount());
        assertFalse(p.getAsyncMode());
        assertEquals(0, p.getQueuedSubmissionCount());
        assertFalse(p.hasQueuedSubmissions());
        while (p.getActiveThreadCount() != 0
               && millisElapsedSince(startTime) < LONG_DELAY_MS)
            Thread.yield();
        assertFalse(p.isShutdown());
        assertFalse(p.isTerminating());
        assertFalse(p.isTerminated());
        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:51,代码来源:ForkJoinPool8Test.java


注:本文中的java.util.concurrent.ForkJoinPool.execute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。