天天看點

java異步擷取結果_java 利用Future異步擷取多線程任務結果

importjava.util.ArrayList;importjava.util.List;importjava.util.Random;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;

public classAsyncThread {public static voidmain(String[] args) {

AsyncThread t= newAsyncThread();

List> futureList = new ArrayList>();

t.generate(3, futureList);

t.doOtherThings();

t.getResult(futureList);

}

public void generate(int threadNum, List>fList) {

ExecutorService service=Executors.newFixedThreadPool(threadNum);for (int i = 0; i < threadNum; i++) {

Future f =service.submit(getJob(i));

fList.add(f);

}

service.shutdown();

}

public voiddoOtherThings() {try{for (int i = 0; i < 3; i++) {

System.out.println("do thing no:" +i);

Thread.sleep(1000 * (new Random().nextInt(10)));

}

}catch(InterruptedException e) {

e.printStackTrace();

}

}

public void getResult(List>fList) {

ExecutorService service=Executors.newSingleThreadExecutor();

service.execute(getCollectJob(fList));

service.shutdown();

}

public Callable getJob(final inti) {final int time = new Random().nextInt(10);return new Callable() {

@Overridepublic String call() throwsException {

Thread.sleep(1000 *time);return "thread-" +i;

}

};

}

public Runnable getCollectJob(final List>fList) {return newRunnable() {public voidrun() {for (Futurefuture : fList) {try{while (true) {if (future.isDone() && !future.isCancelled()) {

System.out.println("Future:" +future+ ",Result:" +future.get());break;

}else{

Thread.sleep(1000);

}

}

}catch(Exception e) {

e.printStackTrace();

}

}

}

};

}

}