ListenableFuture demo

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

public class ListenableFutureTest2 {

	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		ListeningExecutorService executor = MoreExecutors
				.listeningDecorator(Executors.newFixedThreadPool(1));

		final ListenableFuture<String> future = executor
				.submit(new Callable<String>() {
					public String call() throws Exception {
						return "Hello listenable future";
					}
				});

		final ListenableFuture<String> future2 = executor
				.submit(new Callable<String>() {
					public String call() throws Exception {
						Thread.sleep(10000);
						return "Hello listenable future2";
					}
				});

		List<ListenableFuture<String>> futures = Lists.newArrayList();
		
		futures.add(future);
		futures.add(future2);

		ListenableFuture<List<String>> futureAll = Futures
				.successfulAsList(futures);

		System.out.println(Arrays.toString(futureAll.get().toArray()));

		System.out.println("exit..");
	}
}

猜你喜欢

转载自m635674608.iteye.com/blog/2259525