线程安全删除/添加元素从一个列表到另一个列表

zkr*_*tic 1 java multithreading iterator list thread-safety

假设我有两个列表:fooListbarList.另外,假设我有两个线程:第一个迭代fooList,如果满足某些条件(条件为真),它会从fooList中删除元素并将其添加到barList.第二个迭代barList,如果某个其他条件为true,则从barList中删除元素,并将其添加到fooList.

我处理它的方式是:

private static Object sharedLock = new Object();

Thread t1 = new Thread() {
    public void run() {
        synchronized (sharedLock) {

            for (Iterator<String> iterator = fooList.iterator(); iterator.hasNext();) {
                String fooElement = iterator.next();
                if (condition == true) {

                    iterator.remove();
                    barList.add(fooElement);

                }
            }

        }
    }
};

Thread t2 = new Thread() {
    public void run() {
        synchronized (sharedLock) {

            for (Iterator<String> iterator = barList.iterator(); iterator.hasNext();) {
                String barElement = iterator.next();
                if (otherCondition == true) {

                    iterator.remove();
                    fooList.add(barElement);

                }
            }

        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我想知道的是我处理得当吗?是否存在竞争条件?有没有更好的方法来实现相同的功能?

编辑看起来正确的实现方式是:

Thread t1 = new Thread() {
    public void run() {

        for (String fooElement : fooList) {
            if (condition == true) {

                fooList.remove(fooElement);
                barList.add(fooElement);

            }
        }

    }
};

Thread t2 = new Thread() {
    public void run() {

        for (String barElement : barList) {
            if (otherCondition == true) {

                barList.remove(barElement);
                fooList.add(barElement);

            }
        }

    }
};
Run Code Online (Sandbox Code Playgroud)

两者都是:fooListbarList类型CopyOnWriteArrayList<String>

Boh*_*ian 9

不要重新发明轮子:使用ListJDK 的线程安全实现:

List<String> fooList = new CopyOnWriteArrayList<>();
Run Code Online (Sandbox Code Playgroud)

javadoc