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());
    }

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

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

                    return resultStatus;
                }
            });

3.执行多条数据发送

        List> listResult = new ArrayList<>();
        for (int i = 0; i < receivers.size(); i++) {
            final Integer integer = receivers.get(i);
            Future future = service.submit(new Callable() {
                @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

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

参考

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

你可能感兴趣的:(android)