字符串线程是否由于不变性而安全? [英] String thread safety because of immutability?

查看:60
本文介绍了字符串线程是否由于不变性而安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我读到一个字符串是线程安全的,因为它是不可变的.

Hi was reading about that a string is thread safe because it is immutable.

例如我这样做:

String a = "test";

一个线程使用此变量. 但是另一个线程仍然可以使用此变量并对其进行更改:

One thread uses this variable. But another thread could still also use this variable and change it:

a = a + "something";

那么它会改变还是不会改变?

So it would change or not?

如果它是易失性的,我会明白的,它一次只能被一个线程使用.但是不变性并不能保证我!!

If it would be volatile, i would get it, that it can just be used by one thread at a time. But immutabilty doesnt guarantee me this!?

推荐答案

您不是要更改a指向的对象,而是a指向的对象:

You're not changing the object pointed by a, but where a points to:

String a = "test";

此处a指向字符串"test"

a = a + "something";

在此,作为"test""something"的连接的结果,将创建一个新字符串,其中"testsomething"指向该字符串.这是一个不同的实例.

here a new string is created as the result of the concatenation of "test" and "something", which "testsomething" where a points to. It's a different instance.

因此,线程安全性没有问题,因为两个线程都有自己的a引用相同的"test"字符串对象,但是一旦其中一个线程将修改字符串以引用"testsomething"对象,另一个Thread仍将引用原始的"test"对象.

So there is no problem of thread safety, as both threads will have their own a referring to the same "test" string object, but once one of those thread will modify the string to be referring the "testsomething" object, the other Thread will still be referring the original "test" object.

这篇关于字符串线程是否由于不变性而安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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