我的需求就是在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();
}
}Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
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;
}
}
}