多线程:使用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");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值