【发布时间】:2017-03-26 08:38:16
【问题描述】:
public class Test {
public static String str = "abc";
public static void main(String[] args) {
System.out.println("before run" + str);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {;}
str =str +"1";
}
}).start();
}
System.out.println("after run" + str);
}
}
我对不可变类 String 进行了测试,它是一个线程安全的类,所以我想我不必做同步的东西
但是当结果出现时让我感到震惊 “在 abc 之前”和“在 abc 之后”。
当我删除那些 Thread.sleep(100);结果变成了 “在 abc 之前”和“在 abc1111 之后”。
public static String str被修改了,为什么?
【问题讨论】:
-
您不是在修改 string,而是在修改引用它的 variable。为什么要给你存货?
-
我看不到您可以修改字符串的值(例如“运行前”)...确实可以更改变量的值...但它与类型无关不可变...
-
你没有改变一个字符串(因为字符串是不可变的,这是不可能的)。您正在为静态变量分配一个新字符串。这与不变性和线程无关。只做
String s = "a"; s = "b";的可能性。 -
如果您想确保
str不会改变,您可以通过将其声明为final:public static final String str = "abc";。
标签: java string multithreading thread-safety