在线程中处理后输出结果 [英] Output the result after processing in a Thread

查看:41
本文介绍了在线程中处理后输出结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序有一个thr()函数,该函数返回一个字符串值,但是在返回之前,该值在Thread中被覆盖,但是在main()中调用时,此函数将返回在Thread中进行处理之前的字符串.如果添加睡眠",以前一切都会好起来,但是我认为这不是解决问题的好方法.如果对如何解决此问题有建议,那就不好了.

My program has a thr () function that returns a string value, but before returning, the value is overridden in Thread, but when called in main (), this function will return the string that was before being processed in Thread. If you add Sleep, everything will be fine before, but I think this is not a good solution to the problem. If there are suggestions on how to solve this problem, then it would be bad.

代码:

fun main() {
    println(thr())
}

fun thr(): String {
    var x = "Before thread"
    Thread {
        x = "After thread"
    }.start()
//     Thread.sleep(100)
    
    return x
}

期望的结果是-线程后"
当前结果-线程之前"

The desired result is - "After thread"
The current result - "Before thread"

推荐答案

您有一个竞争条件,因为return语句中 x 的值取决于您创建的线程是否已运行并执行了该操作还行- Thread.sleep 仅使当前线程(正在执行 thr()的线程,而不是您正在创建的线程)等待,因此新线程有机会完成.

You have a race condition, because the value of x at the return statement depends on whether your created thread has run and executed that line yet - Thread.sleep just makes the current thread (the one that's executing thr(), not the one you're creating) wait so the new one has a chance to finish.

还有一个问题是线程1看到的 x 的值可能不是线程2看到的,因此它在返回值时看不到更新的值.这取决于提高性能的一些底层内存技巧,这就是为什么您需要处理同步的原因.

There's also the issue that the value of x that Thread 1 sees might not be what Thread 2 sees, so it won't see the updated value at the point where it's returning it. This is down to some under-the-hood memory trickery that improves performance, and it's why you need to handle synchronization.

基本上,您需要阅读并发及其可以使用的不同处理方式.这是针对Java的,但这也是Kotlin中线程处理的基础知识:

Basically you need to read up on concurrency and the different ways it can be handled. This is for Java but it's the basics of what's going on with threading in Kotlin too:

https://docs.oracle.com/javase/tutorial/essential/并发/

您需要大致了解这些内容,因此值得一试!

You need to be aware of this stuff in general, so it's worth getting your head around it!

这篇关于在线程中处理后输出结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆