Objeto futuro con mencionado tiempo de espera es seguir aumentando durante los siguientes temas (timeout no está aplicando para todos los hilos en el ThreadPool en Java)

prudvi Raju:

El subproceso de trabajo se define aquí con pesada tarea de 10 segundos en el método run

import java.util.Date;
import java.util.Random;
import java.util.concurrent.Callable;

public class WorkerThread implements Callable {

private String command;
private long startTime;
public WorkerThread(String s){
    this.command=s;
}

@Override
public Object call() throws Exception {
    startTime = System.currentTimeMillis();
    System.out.println(new Date()+"::::"+Thread.currentThread().getName()+" Start. Command = "+command);
    Random generator = new Random(); 
    Integer randomNumber = generator.nextInt(5); 
    processCommand();
    System.out.println(new Date()+ ":::"+Thread.currentThread().getName()+" End.::"+command+"::"+ (System.currentTimeMillis()-startTime));
    return randomNumber+"::"+this.command;
}

private void processCommand() {
    try {
        Thread.sleep(10000);
    } 
    catch (Exception e) {

        System.out.println("Interrupted::;Process Command:::"+this.command);
    }
}

@Override
public String toString(){
    return this.command;
}

}

Definido mi WorkerPool con el Futuro obtener tiempo de espera de 1 segundo.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class WorkerPool {

        static BlockingQueue queue=new LinkedBlockingQueue(2);
        static RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
        static ThreadFactory threadFactory = Executors.defaultThreadFactory();
        static ThreadPoolExecutor executorPool = new ThreadPoolExecutor(4, 4, 11, TimeUnit.SECONDS, queue, threadFactory, rejectionHandler);
        static MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
        public static void main(String args[]) throws InterruptedException, TimeoutException{
            List<Future<Integer>> list = new ArrayList<Future<Integer>>();
            for(int i=1; i< 5; i++){
                WorkerThread worker = new WorkerThread("WorkerThread:::_"+i);
                Future<Integer> future = executorPool.submit(worker);
                list.add(future);
            }

            for(Future<Integer> future : list){
                try {
                    try {
                        future.get(1000, TimeUnit.MILLISECONDS);
                    } catch (TimeoutException e) {
                        future.cancel(true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            executorPool.shutdown();
        }

    }

El tiempo de espera de la rosca es mantener incresaing de los hilos futuros, Mi expectativa debe ser que si todos los hilos están tomando más de 1 segundo debe cerrar todas a la vez con el! segundo.

En el escenario aboce, subproceso de trabajo se está llevando a 10 seg proceso, pero im el tiempo de espera todos mis 4 hilos con de 1 segundos, pero cada vez que el aumento de hilo incrementaly en 1 segundo para cada tarea.

primero thred tiempo de espera es de 1 segundo segundo thred tiempo de espera es 2 Segunda tercera thred tiempo de espera es de 3 segundos.

¿Por qué no todas las discusiones interupen en 1 segundo a sí misma? Cualquier problema con mi código?

Adam Kotwasins sigue:

Porque está esperando secuencialmente en un bucle en esta sección:

for(Future<Integer> future : list) {
  ...
  future.get(1000, TimeUnit.MILLISECONDS);
  ...
}

Básicamente, el flujo es:

 - all workers 1 .. 4 start
 - you wait for worker A to finish
 - 1 second passes, TimeoutException (worker A was alive for 1 second)
 - you wait for worker B to finish
 - 1 second passes, TimeoutException (worker B was alive for 2 seconds)
 - you wait for worker C to finish
 - 1 second passes, TimeoutException (worker C was alive for 3 seconds)
 - ... same for D ...

Si desea esperar a que como máximo 1 segundo durante todos los trabajadores que necesita para contar la cantidad de tiempo que pasa esperando hasta el momento, y luego esperar que el tiempo restante. Algo así como el pseudocódigo:

long quota = 1000
for (Future future : futures) {
  long start = System.currentTimeMillis
  try {
    future.get(quota, MILLISECONDS)
  }
  catch (TimeoutException e) {
    future.cancel(true)
  }
  finally {
    long spent = System.currentTimeMillis() - start
    quota -= spent
    if (quota < 0) {quota = 0} // the whole block is going to execute longer than .get() only
  }
}


Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=277083&siteId=1
Recomendado
Clasificación