2016-03-04 88 views
0

我一直在使用線程向鏈接發送GET請求(都是好的)。但是,我需要它異步運行,所以我創建了一個新線程並運行它。問題是我需要它在線程完成執行後返回值returnVar[0]。我已經嘗試while循環與!thread.isActive,但當然,方法主體需要一個返回語句。我已經嘗試過CountdownLatche這是你將要看到的,但是他們暫停了我不想要的主線程。任何想法,不勝感激。異步運行任務並在線程激活後返回

代碼:

public String getUUID(String username) { 
    final String[] returnVar = {"ERROR"}; 
    final CountDownLatch latch = new CountDownLatch(1); 

    Thread thread = new Thread(() -> { 

     final String[] response = {"ERROR"}; 
     final JSONObject[] obj = new JSONObject[1]; 

     response[0] = ConnectionsManager.sendGet("https://api.mojang.com/users/profiles/minecraft/" + username); 

     try { 
      obj[0] = (JSONObject) new JSONParser().parse(response[0]); 
      returnVar[0] = (String) obj[0].get("id"); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 

     latch.countDown(); 
    }); 

    thread.start(); 


    try { 
     latch.await(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 

    return returnVar[0]; 
} 

回答

1

我想你應該考慮使用Callable,而不是一個Runnable。有關說明和示例,請參閱this thread

此外,你有一個線程使用CountDownLatch有點奇怪。該鎖定對於確保多個線程儘可能均勻地啓動是有用的,而不是某些線程在更傳統的啓動中獲得「首發」。

0

這是Thread的不當使用。

你的代碼運行完全一樣,下面的代碼:

public String getUUID(String username) { 
    String response = ConnectionsManager.sendGet("https://api.mojang.com/users/profiles/minecraft/" + username); 
    try { 
     return (String) ((JSONObject) new JSONParser().parse(response)).get("id"); 
    } catch (ParseException e) { 
     return "ERROR"; 
    } 
} 

有幾個選項進行異步調用。

一個選擇是使用CompletableFuture

CompletableFuture.supplyAsync(getUUID("username")).thenAccept(new Consumer<String>() { 
    @Override 
    public void accept(String response) { 
     // response of async HTTP GET 
    } 
}); 

瞭解更多: