2017-11-25 18 views
0

我有一個方法。在這個方法中,我由Executors運行一個任務。其工作是從服務器獲取數據並填寫結果Arraylist。countinue Executors.newFixedThreadPool完成其作業後的方法

public Paginator(String secSrv, int total, ExecutorService executorService, Cookie cookie) { 
    securitySrv = secSrv; 
    totalItems = total; 
    this.executorService = executorService; 
    this.cookie = cookie; 
} 

ArrayList<Suser> results = new ArrayList<>(); 

public ArrayList<Suser> generatePage(int currentPage) { 

    fetchAllUsers(currentPage); 
    ...... 
    for (int i = startItem; i < startItem + numOfData; i++) { 
      pageData.add(results.get(i-1)); 
     } 

填充後的結果ArrayList中我必須使用此arraylist.how coud我知道ExecutorService的完成自己的工作,我可以再繼續我的方法是什麼?

private void fetchAllUsers(final int currentPage) { 

    Runnable fetchUserListFromSrv = new Runnable() { 
     @Override 
     public void run() { 
      android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); 
      JSONObject count = new JSONObject(); 
      try { 
       count.put("count", 10); 
       count.put("page", currentPage); 
       String SearchUsersPagingResult = ... 
       results.addAll(susers) ; 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 
    }; 

    executorService.submit(fetchUserListFromSrv); 
} 

回答

1

使用文檔。所有的答案都在這裏。

Future| Android developers

ExecutorService| Android developers

+0

哥們我我的代碼更改爲這一切都是ok.http://codepad.org/C9swPyU5。你能向我解釋一下,這個方法是否存在一個主線程,並且在完成它的工作之後又恢復主線程? – Groot

+0

Future表示異步計算的結果。可調用接口類似於Runnable,因爲它們都是爲其實例可能由另一個線程執行的類設計的。所以,回答你的問題是NO,方法fetchAllUsers()不會阻塞主線程。 –

+0

好的,但爲什麼其他代碼到主線程方法'generatePage(int currentPage)'不執行,直到我的線程完成其工作?如果這些代碼進入主要方法執行我得到錯誤? – Groot

相關問題