我的需求就是在android 中,需要異步上傳一批圖片檢測,但是結(jié)果要按順序加入list中,相當(dāng)于調(diào)用方法有序,但回調(diào)無序,如何解決?
下面是模擬代碼,如何實現(xiàn)在新建線程的情況下保證list.add方法正常,按序執(zhí)行
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年軟件開發(fā)和IT教學(xué)經(jīng)驗。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項目經(jīng)理、高級軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
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; ????????????} ????????} ????}
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號