【问题标题】:Asynchronously running a task and returning after thread is active异步运行任务并在线程处于活动状态后返回
【发布时间】:2016-06-18 15:48:15
【问题描述】:

我一直在使用线程向链接发送 GET 请求(一切都很好)。但是,我需要它异步运行,所以我创建了一个新线程并运行它。问题是我需要它在线程完成执行后返回值returnVar[0]。我曾尝试使用!thread.isActive 进行while 循环,但当然,方法体需要一个return 语句。我已经尝试过您即将看到的CountdownLatches,但他们暂停了我不想要的主线程。任何想法都非常感谢。

代码:

    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];
}

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    我认为您应该考虑使用Callable 而不是Runnable。有关说明和示例,请参阅this thread

    另外,你在一个线程中使用CountDownLatch 有点奇怪。闩锁有助于确保尽可能均匀地启动多个线程,而不是在更传统的启动中让某些线程“抢占先机”。

    【讨论】:

      【解决方案2】:

      这是对Threads 的不当使用。

      您的代码运行方式与以下代码完全相同:

      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
          }
      });
      

      了解更多:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        • 2012-11-26
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多