Future objet avec timeOut mentionné est de plus en plus pour les garder prochaines discussions (timeOut n'applique pas pour tous les fils dans le ThreadPool en Java)

prudvi Raju:

Le thread de travail est défini ici avec la lourde tâche de 10 secondes dans la méthode d'exécution

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;
}

}

Défini mon WorkerPool avec l'avenir obtenir Délai d'attente de 1 seconde.

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();
        }

    }

Le délai d'attente du fil est de garder incresaing pour les fils futurs, mon attente devrait être que si tous les fils prennent plus de 1 seconde devrait fermer tout à la fois avec la! seconde.

Dans le scénario de aboce, thread de travail prend 10 secondes à traiter, mais le calendrier im toutes mes 4 fils avec en 1 secondes, mais à chaque fois de plus en plus fil incrementaly de 1 seconde pour chaque tâche.

Thred premier délai d'attente est une deuxième seconde Thred timeout est 2 Deuxième troisième délai d'attente est Thred 3 II.

Pourquoi toutes les discussions ne sont pas interupting en 1 seconde elle-même? Tout problème avec mon code?

Adam suit Kotwasins:

Parce que vous êtes en attente séquentiellement dans une boucle dans cette section:

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

Fondamentalement, le flux est:

 - 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 vous voulez attendre au plus 1 seconde pour tous les travailleurs dont vous avez besoin de compter combien de temps vous avez passé à attendre jusqu'à présent, puis attendre que le temps restant. Quelque chose comme le pseudo - code:

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
  }
}


Je suppose que tu aimes

Origine http://43.154.161.224:23101/article/api/json?id=277081&siteId=1
conseillé
Classement