1

考虑您有一个共享内存(列表),它将用作“批评部分”。
现在,考虑您在这些场景的列表中总是有项目,并且您希望您的系统以这种方式运行:

  1. Thread1 从列表中获取一些项目,同时 Thread2 想要将项目添加到列表中。允许这种情况(假设我将从头开始获取第一个项目并将新项目插入列表末尾 - 在同一时间!)。

  2. Thread1 想要获得一个项目,同时 Thread2 也想要获得一个项目。这应该失败。

谢谢

4

1 回答 1

1

One possibility is to wrap your List in a class that proxies or overrides the get and add methods.

That way, you can use an explicit Lock on the add method, so that only one thread can add at any given time.

See for instance:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

You could do this either by extending a List implementation, and overriding the add and get methods (or all relevant methods), or by using composition instead of inheritance, having a proxy class that forwards the calls to the list, but decorates the add and get with the explicit obtaining of the Lock.

A very simple example would be something like:

public class SharedMemory<K> {

private final List<K> memoryList;
private static final ReentrantLock lock = new ReentrantLock();

public SharedMemory() {
    memoryList = new ArrayList<>();
}

public void storeItem(K item) {
    memoryList.add(item);
}

public K getItem(int pos){
    lock.lock();
    try{
        return memoryList.get(pos);
    } finally {
        lock.unlock();
    }
}
}
于 2013-01-28T16:56:01.307 回答