Java多线程与并发应用-(8)-Callable和Future

demo1: 使用FutureTask和Callable,获取一个线程的返回值。在获取返回值前可以做其他事,在Future.get()时阻塞,也可调用

get(long timeout, TimeUnit unit)方法设置在等待long时间后如果还没有返回值抛出异常。

package com.lipeng;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class FutureAndCallable1 {

	/**
	 * 使用FutureTask和Callable
	 * @param args
	 */
	public static void main(String[] args)throws Exception  {
		//FutureTask实现了Runnalbe接口,所以可以用来构造Thread.
		//FutureTask实现了Callable接口,可以通过get获取线程返回值
		FutureTask<String> futureTask=new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(3000);
				return "hello";
			}
		});
		new Thread(futureTask).start();
		System.out.println("线程开始。。。。。。");
		//doSomeThing
		System.out.println(futureTask.get());
	}

}

demo2:使用ExecutorService的submit(Callable c)方法

package com.lipeng;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureAndCallable2 {

	/**
	 * 使用ExecutorService的submit(Callable c)方法
	 * @param args
	 */
	public static void main(String[] args)throws Exception  {
		ExecutorService executorService=Executors.newFixedThreadPool(3);
		Future<String> future=executorService.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(3000);
				return "hello";
			}
		});
		System.out.println("--------");
		System.out.println(future.get());
	}

}

3 同时执行多次call方法,返回多个返回值,谁先执行完谁先返回

package com.lipeng;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FutureAndCallable2 {

	/**
	 * 使用ExecutorService的submit(Callable c)方法
	 * @param args
	 */
	public static void main(String[] args)throws Exception  {
		ExecutorService executorService=Executors.newFixedThreadPool(3);
		CompletionService<Integer> cs=new ExecutorCompletionService(executorService);
		for(int i=0;i<10;i++)
		{
			final int j=i;
			cs.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					int time=new Random().nextInt(5000);
					Thread.sleep(time);
					
					return j;
				}
			});
		}
		
		System.out.println("---------------------------");
		for(int i=0;i<10;i++)
		{
			int a=cs.take().get();
			System.out.println(a);
		}
		executorService.shutdown();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值