Wait until any of Future is done

前端 未结 8 1082
长发绾君心
长发绾君心 2021-02-01 01:09

I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I\'ll need to wait util M out of N tasks are finished). C

8条回答
  •  抹茶落季
    2021-02-01 01:14

    See this option:

    public class WaitForAnyRedux {
    
    private static final int POOL_SIZE = 10;
    
    public static  T waitForAny(Collection collection) throws InterruptedException, ExecutionException {
    
        List> callables = new ArrayList>();
        for (final T t : collection) {
            Callable callable = Executors.callable(new Thread() {
    
                @Override
                public void run() {
                    synchronized (t) {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                }
            }, t);
            callables.add(callable);
        }
    
        BlockingQueue queue = new ArrayBlockingQueue(POOL_SIZE);
        ExecutorService executorService = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 0, TimeUnit.SECONDS, queue);
        return executorService.invokeAny(callables);
    }
    
    static public void main(String[] args) throws InterruptedException, ExecutionException {
    
        final List integers = new ArrayList();
        for (int i = 0; i < POOL_SIZE; i++) {
            integers.add(i);
        }
    
        (new Thread() {
            public void run() {
                Integer notified = null;
                try {
                    notified = waitForAny(integers);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                System.out.println("notified=" + notified);
            }
    
        }).start();
    
    
        synchronized (integers) {
            integers.wait(3000);
        }
    
    
        Integer randomInt = integers.get((new Random()).nextInt(POOL_SIZE));
        System.out.println("Waking up " + randomInt);
        synchronized (randomInt) {
            randomInt.notify();
        }
      }
    }
    

提交回复
热议问题