Return values from Java Threads

后端 未结 9 1406
耶瑟儿~
耶瑟儿~ 2020-12-13 07:12

I have a Java Thread like the following:

   public class MyThread extends Thread {
        MyService service;
        String id;
        public MyThread(Stri         


        
9条回答
  •  无人及你
    2020-12-13 07:54

    In Java8 there is better way for doing this using CompletableFuture. Say we have class that get's id from the database, for simplicity we can just return a number as below,

    static class GenerateNumber implements Supplier{
    
        private final int number;
    
        GenerateNumber(int number){
            this.number = number;
        }
        @Override
        public Integer get() {
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            return this.number;
        }
    }
    

    Now we can add the result to a concurrent collection once the results of every future is ready.

    Collection results = new ConcurrentLinkedQueue<>();
    int tasks = 10;
    CompletableFuture[] allFutures = new CompletableFuture[tasks];
    for (int i = 0; i < tasks; i++) {
         int temp = i;
         CompletableFuture future = CompletableFuture.supplyAsync(()-> new GenerateNumber(temp).get(), executor);
         allFutures[i] = future.thenAccept(results::add);
     }
    

    Now we can add a callback when all the futures are ready,

    CompletableFuture.allOf(allFutures).thenAccept(c->{
       System.out.println(results); // do something with result
    });
    

提交回复
热议问题