java - 异步运行任务并在线程 Activity 后返回

标签 java multithreading

我一直在使用线程向链接发送 GET 请求(一切都很好)。但是,我需要它异步运行,所以我创建了一个新线程并运行它。问题是我需要它在线程执行完毕后返回值 returnVar[0] 。我尝试过使用 !thread.isActive 进行 while 循环,但是当然,方法主体需要一个 return 语句。我已经尝试过您即将看到的 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];
}

最佳答案

我认为您应该考虑使用Callable而不是Runnable。请参阅this thread以获得解释和示例。

此外,您在一个线程中使用 CountDownLatch 有点奇怪。锁存器对于确保多个线程尽可能统一地启动非常有用,而不是某些线程在更传统的启动中“领先”。

关于java - 异步运行任务并在线程 Activity 后返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804017/

相关文章:

java - 如何以用户身份在 Parse 上存储和加载 session ?

Java Android - XmlPullParser - 如何再次从头开始解析?

java - CountDownLatch等待方法问题: doesn't throw on timeout

C#:我不能在 ThreadStart 中使用匿名委托(delegate)吗?

java - 使用 Gson 序列化一个 POJO

java - 如何限制 JMS DefaultMessageListenerContainer 重试消息的次数?

c++ - 由于异常而展开时处理 C++ 析构函数中的 pthread 取消点

java - 生产者-消费者生产一件元素并立即消费(Java)

初始化错误thread-10中的Java异常

java - 该方法添加 mod 2^512