【发布时间】:2023-03-28 02:13:01
【问题描述】:
在学习 Java 并发时,我遇到了这种我无法解释的行为:
public class ThreadInterferrence implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ThreadInterferrence());
t.start();
append("1", 50);
t.join();
System.out.println(value);
}
private static String value = "";
public void run() {
append("2", 50);
}
private static void append(String what, int times) {
for (int i = 0; i < times; ++i) {
value = value + what;
}
}
}
为什么程序会生成随机字符串?更重要的是为什么输出的长度不同?它不应该总是正好 100 个字符吗?
输出示例:
22222222222222222222222222222222222222222222222222
1111111111111111111111111111112121112211221111122222222222222
等等。
【问题讨论】:
标签: java string multithreading concurrency terminate