Android 多线程发送消息(Future、Callable)

多线程实现方式主要有三种:

  1. 继承Thread类
  2. 实现Runnable接口
  3. 使用ExecutorService、Callable、Future

 

第1,2两种是没有返回结果的,第3是带有返回结果

处理多线程发送消息用的是第3种,其是通过实现Callable接口,并用Future可以来接收多线程的执行结果。

 

AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减,适合高并发情况下的使用

使用方法  AtomicInteger ai = new AtomicInteger(0);  使用的时候需要传入一个初始化值

/**
     * Creates a new AtomicInteger with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicInteger(int initialValue) {
        value = initialValue;
    }

常用的方法,递增

/**
     * Atomically increments by one the current value.
     *
     * @return the updated value
     */
    public final int incrementAndGet() {
        return U.getAndAddInt(this, VALUE, 1) + 1;
    }

常用的方法,递减 



    /**
     * Atomically decrements by one the current value.
     *
     * @return the updated value
     */
    public final int decrementAndGet() {
        return U.getAndAddInt(this, VALUE, -1) - 1;
    }

下面开始处理多线程发送消息

1.创建线程池

private static ExecutorService service = Executors.newFixedThreadPool(100);

上面100是线程数量,不能小于0,否则会报错 

 /**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * {@code nThreads} threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

2.设置发送消息请求 及 设置多线程的执行结果

        Future<Integer> future = service.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                     //调用相对比较耗时的发送消息接口
                    Thread.sleep(200);
                    int resultStatus = 0;//发送结果状态
                    //todo 请求发送消息处理
                    .....

                    return resultStatus;
                }
            });

3.执行多条数据发送

        List<Future<Integer>> listResult = new ArrayList<>();
        for (int i = 0; i < receivers.size(); i++) {
            final Integer integer = receivers.get(i);
            Future<Integer> future = service.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    //调用相对比较耗时的发送消息接口
                    Thread.sleep(200);
                    int resultStatus = 0;//发送结果状态
                    //todo 请求发送消息处理
                    .....

                    return resultStatus;
                }
            });
            list.add(future);
        }

4.处理发送结果状态,统计发送情况

AtomicInteger ai = new AtomicInteger(0);
 for(int i=0;i<listResult.size();i++){
        try {
              int resultStatus = list.get(i).get();
              if(resultStatus == 1){//发送成功
                    ai.incrementAndGet();
                }
         } catch (Exception e) {
                e.printStackTrace();
         }
    }

以上就是大概的简单思路,项目实战中还是需要考虑的更细致的,比如说请求时间过长的处理,请求失败的处理等方面

参考

https://www.cnblogs.com/quanenmin/p/4914620.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值