简体   繁体   English

如何在kotlin中从线程中提取返回值

[英]How to extract return value from Thread in kotlin

Assume I have a function in which I send a http request and get the results.假设我有一个函数,可以在其中发送 http 请求并获取结果。 Obviously, I have some wait inside it:显然,我在里面有一些等待:

fun getDocuments(): JsonObject {
        Thread {
            return@Thread functionToGetHttpResultAsJsonObject()
        }.start()
    }

What I need is to extract return value of functionToGetHttpResultAsJsonObject() into getDocuments() return value.我需要的是将 functionToGetHttpResultAsJsonObject() 的返回值提取到 getDocuments() 返回值中。 But I get Unit instead my desired JsonObject.但是我得到了 Unit 而不是我想要的 JsonObject。 Any help will be appreciated任何帮助将不胜感激

Let's start that your request is a bit strange.让我们开始说你的要求有点奇怪。 You normally don't spin a thread to block the main thread waiting for it to finish.您通常不会旋转线程来阻止主线程等待它完成。 The main point of threads is to not do that, that said.线程的要点是不要那样做。

There is no simple way to pass information between threads.没有简单的方法可以在线程之间传递信息。

If you want to wait for a thread to finish inside another thread you should call .join() instead of .start()如果你想等待一个线程在另一个线程内完成,你应该调用.join()而不是.start()

But that will not return anything.但这不会返回任何东西。 If you want to synchronize two threads.如果要同步两个线程。 So one waits for the other to compute some data and get that data, one way to do it is to use a BlockingQueue因此,一个等待另一个计算一些数据并获取该数据,一种方法是使用BlockingQueue

val queue = LinkedBlockingQueue<Int>()

Thread {
    println("concurrency ftw")
    Thread.sleep(1_000)
    println("finish sleeping!")
    queue.add(1)
}.start()

println("first")
println(queue.take())

Notice I'm using .start() here because I don't want to block the second Thread to do it's processing.注意我在这里使用.start()是因为我不想阻塞第二个线程来完成它的处理。

The main thread will block at the .take until someone adds some data.主线程将在.take.take直到有人添加一些数据。 At the same time, if the second thread arrived first to the .add it will also block until someone consumes that data.同时,如果第二个线程首先到达.add它也会阻塞,直到有人使用该数据。

At this point I also should mention that Kotlin has the concept of coroutines.在这一点上我还应该提到 Kotlin 有协程的概念。 They are very similar in concept to Go "channels" and I would advice to look into those as well .它们在概念上与 Go 的“通道”非常相似,我建议也研究这些

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM