有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java理解同步程序的行为

我试图提高对synchronized调用期间发出的锁的范围的理解

例如:

class CopyOnReadList<T> {

    private final List<T> items = new ArrayList<T>();

    public void add(T item) {
        items.add(item);
    }

    public List<T> makeSnapshot() {
        List<T> copy = new ArrayList<T>();
        synchronized (items) {
            // Make a copy while holding the lock.
            for (T t : items) copy.add(t);
        }
        return copy;
    }

}

(代码亲切地从this excellent answer借用)

在这个代码片段中,一个线程可以调用add,而另一个线程可以调用makeSnapshot?。也就是说,由synchronized (items)创建的锁是否会影响所有试图读取items的操作,或者只影响那些通过makeSnapshot()方法尝试的操作

最初的帖子实际上在add方法中使用了synchonized锁:

public void add(T item) {
    synchronized (items) {
        // Add item while holding the lock.
        items.add(item);
    }
}

去掉这个有什么副作用


共 (1) 个答案

  1. # 1 楼答案

    In this code snippet, can one thread call add while another is calling makeSnapshot?

    当然——然后,其中一个方法可能会失败,并出现ConcurrentModificationException,或者列表的内容可能已损坏

    does the lock created by synchronized (items) affect all attempted reads to items, or only those attempted through the makeSnapshot() method?

    都不是。锁对对象items的行为没有任何影响,只对在其上进行snychroning的块或方法有影响,即确保没有两个线程可以同时执行这些块或方法中的任何一个