Java – warten bis alle Tasks fertig sind

Veröffentlicht von

Hier ein kleines Beispiel, wie man wartet, bis mehrere Tasks fertig sind und danach das Resultat ausliest.

import java.util.concurrent.*;
import java.util.*;

public class InvokeExecutorServiceDemo {
	
    public static void main(String args[]) throws InterruptedException, ExecutionException {
    	InvokeExecutorServiceDemo demo = new InvokeExecutorServiceDemo();
    }
	
    public InvokeExecutorServiceDemo() throws InterruptedException, ExecutionException {
    	
        ExecutorService serviceAny = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        // erstelle Tasks
        List<MyCallable> futureListAny = new ArrayList<MyCallable>();
        for (int i = 0; i < 10; i++){        	
            MyCallable myCallable = new MyCallable((long) i);
            futureListAny.add(myCallable);
        }
        
        System.out.println("Start - invokeAny");  
        System.out.println("----------------------------------"); 
        
        // Wenn einer der Tasks fertig ist, dann weiter
        Long future = serviceAny.invokeAny(futureListAny);
        serviceAny.shutdown();
        
        System.out.println("Completed - invokeAny");
        System.out.println("Result - invokeAny: " + future);
        
//-------------------------------------------------------------------
              
        ExecutorService serviceAll = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        
        // erstelle Tasks
        List<MyCallable> futureListAll = new ArrayList<MyCallable>();
        for (int i = 0; i < 10; i++){
            MyCallable myCallable = new MyCallable((long)i);
            futureListAll.add(myCallable);
        }
        
        System.out.println("\nStart - invokeAll"); 
        System.out.println("----------------------------------"); 
        
        // Wenn alle Tasks fertig sind, dann weiter
        List<Future<Long>> futures = serviceAll.invokeAll(futureListAll);
        serviceAll.shutdown();
        
        System.out.println("Completed - invokeAll");        
        for (Future<Long> item : futures) {
			System.out.println("Result - invokeAll: " + item.get());
		}
    }
   
    class MyCallable implements Callable<Long>{
        Long id = 0L;
        public MyCallable(Long val) {
            this.id = val;           
        }
        public Long call() throws InterruptedException{
            // Add your business logic
        	int randomNum = ThreadLocalRandom.current().nextInt(0, 10);
			Thread.sleep(500 * randomNum);
        	System.out.println(id + ". Thread Finished");
        	
            return id;
        }
    }
}Code-Sprache: PHP (php)