Saturada de análisis de código fuente Estrategia

prefacio

Github: https://github.com/yihonglei/thinking-in-concurrent

Abortar una estrategia

política por defecto, directamente tirado RejectedExecutionException sin marcar cuando una nueva presentación de tareas, la excepción es capturado por la persona que llama.

new ThreadPoolExecutor.AbortPolicy()
/**
 * A handler for rejected tasks that throws a
 * {@code RejectedExecutionException}.
 */
public static class AbortPolicy implements RejectedExecutionHandler {
    /**
     * Creates an {@code AbortPolicy}.
     */
    public AbortPolicy() { }

    /**
     * Always throws RejectedExecutionException.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     * @throws RejectedExecutionException always
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        throw new RejectedExecutionException("Task " + r.toString() +
                                             " rejected from " +
                                             e.toString());
    }
}

estrategia de dos CallerRuns

Para ajustar el mecanismo, no abandonar la tarea no se lanza, pero algunas tareas caerán de nuevo a la persona que llama. No realiza nuevas tareas en el hilo en el grupo de subprocesos,

Pero ejecutar un nuevo hilo exector llamada tarea, que sintonizan es decir, que es responsable de la implementación.

new ThreadPoolExecutor.CallerRunsPolicy()
/**
 * A handler for rejected tasks that runs the rejected task
 * directly in the calling thread of the {@code execute} method,
 * unless the executor has been shut down, in which case the task
 * is discarded.
 */
public static class CallerRunsPolicy implements RejectedExecutionHandler {
    /**
     * Creates a {@code CallerRunsPolicy}.
     */
    public CallerRunsPolicy() { }

    /**
     * Executes task r in the caller's thread, unless the executor
     * has been shut down, in which case the task is discarded.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            r.run();
        }
    }
}

Descartar tres estrategias

La nueva presentación tarea fue abandonado.

new ThreadPoolExecutor.DiscardPolicy()
/**
 * A handler for rejected tasks that silently discards the
 * rejected task.
 */
public static class DiscardPolicy implements RejectedExecutionHandler {
    /**
     * Creates a {@code DiscardPolicy}.
     */
    public DiscardPolicy() { }

    /**
     * Does nothing, which has the effect of discarding task r.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    }
}

estrategia de cuatro DiscardOldest

Cola es el "jefe de equipo", la tarea, y luego tratar de presentar una nueva tarea. cabeza tarea se descartan (no apto para la escena cola de trabajo de cola de prioridad)

new ThreadPoolExecutor.DiscardOldestPolicy()
/**
 * A handler for rejected tasks that discards the oldest unhandled
 * request and then retries {@code execute}, unless the executor
 * is shut down, in which case the task is discarded.
 */
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
    /**
     * Creates a {@code DiscardOldestPolicy} for the given executor.
     */
    public DiscardOldestPolicy() { }

    /**
     * Obtains and ignores the next task that the executor
     * would otherwise execute, if one is immediately available,
     * and then retries execution of task r, unless the executor
     * is shut down, in which case task r is instead discarded.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            e.getQueue().poll();
            e.execute(r);
        }
    }
}

estrategia de procesamiento de saturación de cinco personalizada

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * 循环处理,当队列有空位时,该任务进入队列,等待线程池处理
 */
public class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
  public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    try {
      executor.getQueue().put(r);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

 

Publicados 502 artículos originales · ganado elogios 358 · Vistas 1,18 millones +

Supongo que te gusta

Origin blog.csdn.net/yhl_jxy/article/details/103218700
Recomendado
Clasificación