多线程:使用FutureTask获得线程返回值+同步线程

public class FutureTaskTest {

	public static void main(String[] args) {
		testMultiThreadExecutor();
	}

	public static void testFutureTask() {
		Callable<Integer> callable = new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				for (int i = 0; i < 10; i++) {
					System.out.println("Sleep " + i + " second");
					Thread.sleep(1000);
				}
				return 100;
			}
		};

		FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
		new Thread(futureTask).start();
		try {
			System.out.println("The main thread sleep 3 seconds");
			Thread.sleep(3000);
			System.out.println("The main thread sleep another 3 seconds");
			Thread.sleep(3000);
			System.out.println(futureTask.get());
			System.out.println("end");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,
	 * Executor使我们无需显示的去管理线程的生命周期,是JDK 5之后启动任务的首选方式
	 */
	public static void testSingleThreadExecutor() {
		//返回一个AbstractExecutorService的实现类的对象,AbstractExecutorService实现了submit(Callable), AbstractExecutorService的子类ThreadPoolExecutor中实现了execute(Runnable)
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<Integer> future = threadPool.submit(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				for (int i = 0; i < 10; i++) {
					System.out.println("Sleep " + i + " second");
					Thread.sleep(1000);
				}
				return 200;
			}
		});

		try {
			System.out.println("The main thread sleep 3 seconds");
			Thread.sleep(3000);
			System.out.println("The main thread sleep another 3 seconds");
			Thread.sleep(3000);
			System.out.println(future.get());
			System.out.println("end");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} finally {
			threadPool.shutdown(); // do NOT forget to shutdown thread pool
		}
	}

	public static void testMultiThreadExecutor() {
//		ExecutorService threadPool = Executors.newCachedThreadPool();
		int threadNumber = 5;
		ExecutorService threadPool = Executors.newFixedThreadPool(threadNumber);
		CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
		for (int i = 0; i < threadNumber; i++) {
			final int taskID = i;
			cs.submit(new Callable<Integer>() {
				public Integer call() throws Exception {
					int totalSleep = new Random().nextInt(10);
					for (int i = 0; i < totalSleep; i++) {
						System.out.println(taskID + ": sleep " + i + " second of " + totalSleep);
						Thread.sleep(1000);
					}
					return taskID;
				}
			});
		}
		
		try {
			System.out.println("The main thread sleep 3 seconds");
			Thread.sleep(3000);
			System.out.println("The main thread sleep another 3 seconds");
			Thread.sleep(3000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} finally {
			threadPool.shutdown();
		}
		
		for (int i = 0; i < threadNumber; i++) {
			try {
				System.out.println(cs.take().get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		System.out.println("end");
	}
}

你可能感兴趣的:(JavaSE,Multiple Thread)