私有变量线程安全吗

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)

ayy*_*ani 1

当您认为必须抛出异常时,您应该抛出异常。当两个线程尝试同时修改 person 对象时,您的代码不会引发异常,但在这种情况下您可能会得到不可预测的结果,您应该手动阻止并发修改。