📜  Java的ForkJoinPool 类示例

📅  最后修改于: 2022-05-13 01:55:33.750000             🧑  作者: Mango

Java的ForkJoinPool 类示例

ForkJoinPool类是 fork/join 框架的中心,它是 ExecutorService 接口的实现。 ForkJoinPool 类是AbstractExecutorService 类的扩展,它实现了fork/join 框架的工作窃取算法(即工作线程没有事情做可以从其他仍然忙碌的线程窃取任务)并且可以执行ForkJoinTask过程。

ForkJoinPool 类从Java.util.concurrent.AbstractExecutorService 类继承了以下方法:

  • 调用All()
  • 调用Any()

ForkJoinPool 类从从Java.lang.Object 类继承的方法中继承了以下方法:

  • 克隆()
  • 等于()
  • 完成()
  • 获取类()
  • 哈希码()
  • 通知()
  • 通知所有()
  • 等待()

句法:

public class ForkJoinPool extends AbstractExecutorService  

Fork: Fork 步骤将任务拆分为更小的子任务,这些任务并发执行。



Join:子任务执行完毕后,该任务可以将所有结果合并为一个结果。

如下图所示:

ForkJoinPool-Class-in-Java-with-Examples

例子:

getActiveThreadCount():此方法返回当前正在窃取或执行任务的线程的估计数量。它可能会高估活动线程的数量。

句法

public int getActiveThreadCount()
Java
// Java program to demonstrate the
// Implementation of getActiveThreadCount()
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
class NewTask extends RecursiveAction
{
    private long Load = 0;
     
    public NewTask(long Load) { this.Load = Load; }
 
    protected void compute()
    {
        // fork tasks into smaller subtasks
        List subtasks = new ArrayList();
        subtasks.addAll(createSubtasks());
         
        for (RecursiveAction subtask : subtasks) {
            subtask.fork();
        }
    }
     
    // function to create and add subtasks
    private List createSubtasks()
    {
        // create subtasks
        List subtasks = new ArrayList();
        NewTask subtask1 = new NewTask(this.Load / 2);
        NewTask subtask2 = new NewTask(this.Load / 2);
        NewTask subtask3 = new NewTask(this.Load / 2);
         
        // to add the subtasks
        subtasks.add(subtask1);
        subtasks.add(subtask2);
        subtasks.add(subtask3);
         
        return subtasks;
    }
}
public class JavaForkJoingetActivethreadcountExample1 {
    public static void main(final String[] arguments)
        throws InterruptedException
    {
        // get no. of available core available
        int proc = Runtime.getRuntime().availableProcessors();
         
        System.out.println("Number of available core in the processor is: "
            + proc);
             
        // get no. of threads active
        ForkJoinPool Pool = ForkJoinPool.commonPool();
         
        System.out.println("Number of active thread before invoking: "
            + Pool.getActiveThreadCount());
             
        NewTask t = new NewTask(400);
         
        Pool.invoke(t);
         
        System.out.println("Number of active thread after invoking: "
            + Pool.getActiveThreadCount());
        System.out.println("Common Pool Size is: "
                           + Pool.getPoolSize());
    }
}



输出
Number of available core in the processor is: 4
Number of active thread before invoking: 0
Number of active thread after invoking: 3
Common Pool Size is: 3

ForkJoinPool 类的方法

METHOD

DESCRIPTION

public boolean awaitQuiescence(long timeout, TimeUnit unit)This method executes pool until the pool is quiescent, otherwise, assist performing tasks until specified time value and unit elapses or the pool is quiescent.
public boolean awaitTermination(long timeout, TimeUnit unit) This method blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
public static ForkJoinPool commonPool()This method returns the common pool instance.
public void execute(Runnable task)This method executes the given command at some time in the future.
public int getActiveThreadCount()This method returns an estimated number of threads that are currently stealing or executing tasks. It may overestimate the number of active threads.
public boolean getAsyncMode()This method returns true if this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.
public static int getCommonPoolParallelism()This method returns the targeted parallelism level of the common pool.
public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()This method returns the factory used for constructing new workers.
public int getParallelism()This method returns the targeted parallelism level of this pool.
public int getPoolSize()This method returns the number of worker threads that have started but not yet terminated.
public int getQueuedSubmissionCount()This method returns an estimate of the number of tasks submitted to this pool that have not yet begun executing.
public long getQueuedTaskCount()This method returns an estimate of the total number of tasks currently held in queues by worker threads
public int getRunningThreadCount()This method returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization.
public long getStealCount()This method returns an estimate of the total number of tasks stolen from one thread’s work queue by another.
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()This method returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.
public boolean hasQueuedSubmissions()This method returns true if there are any tasks submitted to this pool that have not yet begun executing.
public T invoke(ForkJoinTask task)This method performs the given task and returns its result upon completion.
public boolean isQuiescent()This method returns true if all worker threads are currently idle.
public boolean isShutdown()This method returns true if the pool calling isShutdown() has been shut down.
public boolean isTerminated()This method returns true if all tasks have completed following shut down.
public boolean isTerminating()This method returns true if the process of termination has started but not yet completed. 
protected RunnableFuture newTaskFor(Callable callable)This method returns a RunnableFuture which, when run, will call the underlying callable and which, as a Future, will yield the callable’s result as its result and provide for cancellation of the underlying task.
public void shutdown()This method returns true if this pool has been shut down.
public List shutdownNow()This method possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks.
public ForkJoinTask submit(Runnable task)This method submits a Runnable task for execution and returns a Future representing that task.
public String toString()This method returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts.