java多线程Future和Callable类示例分享

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。今天我们就来研究下Future和Callable的实现方法

一,描写叙述

    ​在多线程下编程的时候。大家可能会遇到一种需求,就是我想在我开启的线程都结束时,同一时候获取每一个线程中返回的数据然后再做统一处理,在这种需求下,Future与Callable的组合就派上了非常大的用场。

也有人会说,我能够使用同步来完毕这个需求啊,普通情况下确实能够。可是在一种特殊情况下就不行了:

    ​想象,你开启了多个线程同步计算一些数据,可是大家都知道,线程是会争用资源的,也就是说。你开启多个线程来同步计算数据时。事实上线程之间的计算顺序是不可空的,当然除非你非非常大周折去处理也不无可能。在这样的情况下。Future和Callable的组合就是不二之选了。

二,样例

这两个类的样例事实上非常easy,主要就看自己在实际运用中能不能找到他们的用武之地了。上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package test;
  
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
  
public class FetureCallableTest {
   private static ExecutorService service = Executors.newFixedThreadPool( 100 );
   private static int count = 1 ;
   public static void main(String[] args) throws InterruptedException, ExecutionException {
     int sum = 0 ;
     for ( int i = 0 ; i < 100 ; i++) {
       Future<Integer> future = service.submit( new Callable<Integer>(){
    
         @Override
         public Integer call() throws Exception {
           System.out.println(Thread.currentThread().getName());
           return ++count;
         }
          
       });
       int f = future.get();
       sum += f;
       System.out.println( "future is " + f);
     }
     System.out.println( "sum is " + sum);
     service.shutdownNow();
   }
  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值