2016-09-01 71 views
1

我想運行兩個runnables一個接一個線程。android運行多個可運行

這意味着當第一個可運行線程完成第二個線程啓動時。

DownSpeedTester speedTester = new DownSpeedTester(); 
speedTester.setDownUrl(String.valueOf(urlDownload)); 
new Thread(speedTester).start(); 

UploadSpeedTester uploadSpeedTester = new UploadSpeedTester(); 
uploadSpeedTester.setUploadUrl(String.valueOf(urlUpload)); 
new Thread(uploadSpeedTester).start(); 

嘗試使用newSingleThreadExecutor,但它沒有成功。

ExecutorService es = Executors.newSingleThreadExecutor(); 
    Future< Boolean> result = es.submit(new Callable<Boolean>() { 
     public Boolean call() throws Exception { 
      //Download 
      DownSpeedTester speedTester = new DownSpeedTester(); 
      speedTester.setDownUrl(String.valueOf(urlDownload)); 
      new Thread(speedTester).start(); 
      return true; 
     } 
    }); 
    try { 
     boolean res = result.get(); 
     if (res == true){ 
      //Upload 
      Log.d("mceeli","UploadSpeedTester"); 
      UploadSpeedTester uploadSpeedTester = new UploadSpeedTester(); 
      uploadSpeedTester.setUploadUrl(String.valueOf(urlUpload)); 
      new Thread(uploadSpeedTester).start(); 
     } 
    } catch (Exception e) { 

    } 
    es.shutdown(); 

它仍然在一起運行。

請幫幫我。

+0

在第一個回調中調用第二個線程 – Amy

回答

3

可以使用的AsyncTask的運行兩個線程此起彼伏。但如果你想使用線程,你可以使用

private static final int STEP_ONE_COMPLETE = 0; 
private static final int STEP_TWO_COMPLETE = 1; 

... 

private doBackgroundUpdate1(){ 
    Thread backgroundThread = new Thread() { 
     @Override 
     public void run() { 
      // do first step 

      // finished first step 
      Message msg = Message.obtain(); 
      msg.what = STEP_ONE_COMPLETE; 
      handler.sendMessage(msg); 
     } 
    } 
    backgroundThread.start(); 
} 
private doBackgroundUpdate2(){ 
    Thread backgroundThread = new Thread() { 
     @Override 
     public void run() { 
      // do second step 

      // finished second step 
      Message msg = Message.obtain(); 
      msg.what = STEP_TWO_COMPLETE; 
      handler.sendMessage(msg); 
     } 
    } 
    backgroundThread.start(); 
} 
private Handler handler = new Handler(){ 
    @Override 
    public void handleMessage(Message msg) { 
     switch(msg.what){ 
     case STEP_ONE_COMPLETE: 
      doBackgroundUpdate2(); 
      break; 
     case STEP_TWO_COMPLETE: 
      // do final steps; 
      break; 
     } 
    } 
} 
+0

非常感謝! –

1

使用單個線程執行,只是不產卵更多Thread S:

ExecutorService es = Executors.newSingleThreadExecutor(); 
DownSpeedTester speedTester = new DownSpeedTester(); 
speedTester.setDownUrl(String.valueOf(urlDownload)); 
es.submit(speedTester); 

UploadSpeedTester uploadSpeedTester = new UploadSpeedTester(); 
uploadSpeedTester.setUploadUrl(String.valueOf(urlUpload)); 
es.submit(uploadSpeedTester); 

es.shutdown();