Vic*_*cky 5 java multithreading thread-safety concurrentmodification
当两个线程尝试修改对象的数据时,正在开发 api(如 Java 中的 Collections api)的开发人员是否应该手动抛出 ConcurrentModificationException?
为什么这段代码不会在多个线程尝试修改Person's 对象的内容时抛出异常?
public class Main {
public static void main(String[] args) {
// write your code here
RunnableDemo r = new RunnableDemo();
for (int i = 0; i < 10; i++) {
Thread t = new Thread(r, "Thread " + i);
t.start();
}
}
}
class RunnableDemo implements Runnable {
private Person person = new Person();
@Override
public void run() {
for (int i = 0; i < 100; i++) {
person.setName("Person" + i);
System.out.println(person.getName());
}
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1662 次 |
| 最近记录: |