Java Future用法和意义一句话击破

在并发编程时,一般使用runnable,然后扔给线程池完事,这种情况下不需要线程的结果。 
所以run的返回值是void类型。 

如果是一个多线程协作程序,比如菲波拉切数列,1,1,2,3,5,8...使用多线程来计算。 
但后者需要前者的结果,就需要用callable接口了。 
callable用法和runnable一样,只不过调用的是call方法,该方法有一个泛型返回值类型,你可以任意指定。 

线程是属于异步计算模型,所以你不可能直接从别的线程中得到函数返回值。 
这时候,Future就出场了。Futrue可以监视目标线程调用call的情况,当你调用Future的get()方法以获得结果时,当前线程就开始阻塞,直接call方法结束返回结果。 

下面三段简单的代码可以很简明的揭示这个意思: 

1.runnable接口实现的没有返回值的并发编程。 

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 试验 Java 的 Future 用法
 */
public class FutureTest {

    /*
    * step 1:
    * runnable实现的没有返回值的并发编程
    */
    public static class Task implements Runnable{
        @Override
        public void run(){
            System.out.println(Thread.currentThread().getId());
        }
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException{
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i = 0; i < 10; i++){
            es.submit(new Task());
        }
    }
}

2.callable实现的存在返回值的并发编程。(call的返回值String受泛型的影响) 

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 试验 Java 的 Future 用法
 */
public class FutureTest {

    /*
    * step 2:
    * callable实现的有返回值的并发编程
    * call的返回值受泛型的影响
    */
    public static class Task implements Callable<String>{
        @Override
        public String call() throws Exception{
            System.out.println(Thread.currentThread().getId());
            return String.valueOf(Thread.currentThread().getId());
        }
    }
    public static void main(String[] args){
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i = 0; i < 10; i++){
            es.submit(new Task());
        }
    }
}
3. callable实现的存在返回值的并发编程,使用Future获取返回值。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 试验 Java 的 Future 用法
 */
public class FutureTest {

    /*
    * step 3:
    * callable实现的有返回值的并发编程
    * 用future获取返回值
    */
    public static class Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            String tid = String.valueOf(Thread.currentThread().getId());
            System.out.println("Thread :" + tid);
            return tid;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Future<String>> results = new ArrayList<Future<String>>();
        ExecutorService es = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++)
            results.add(es.submit(new Task()));

        for (Future<String> res : results)
            System.out.println(res.get());
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值