异步情况下的循环,怎么解决这个问题
高洛峰
高洛峰 2016-10-27 13:43:07
[Java讨论组]

我的需求就是在android 中,需要异步上传一批图片检测,但是结果要按顺序加入list中,相当于调用方法有序,但回调无序,如何解决?

下面是模拟代码,如何实现在新建线程的情况下保证list.add方法正常,按序执行

public class Test {
    public static void main(String args[]) {
        for (int i = 0; i < 10; ++i) {
            test1(i);
        }
    }

    static List<String> arrayList = new ArrayList<>();

    private static void test1(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    arrayList.add(i, i + "position");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
三叔
public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(10);
        
        List> list = new ArrayList();
        
        for (int i = 0; i  future : exec.invokeAll(list)) {
                try {
                    System.out.println(future.get());
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        exec.shutdown();
    }
    
    static Callable newTask(final int t) {
        return new Callable() {
            @Override
            public Integer call() throws Exception {
                System.out.println("newTask: " + t);
                try {
                    Thread.sleep((10 - t) * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return t;
            }
        }
    }


热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号