在List <string>或Hastable <string,string>上创建锁

时间:2017-12-07 15:20:27

标签: java locking

包含特定值的(String,String)类型的String或Hastable列表。 我有多个线程正在运行的情况,我希望每个线程只使用上述列表中的一个值。

实施例: 列表 - Set1,Set2,Set3

如果Thread1正在使用Set1并且thread2尝试使用列表中的一个值,那么它应该只获得Set2和Set3。完成Thread1后,Set1应该可用。

1 个答案:

答案 0 :(得分:0)

你可以通过锁定List并在开始/完成工作之前删除/添加适当的Set来实现它:

public class ListLock {
    private List<Set<String>> list = new ArrayList<>();

    //initialize with some values
    public ListLock(List<Set<String>> availableValues) {
        this.list = availableValues;
    }

    //this will allow your Thread to get an available value. Your Thread needs to keep the selected value until the job is done and put it back
    public void synchronized aquireValue(Selector selector) {
        //this one is little bit tricky, you provide some interface, that has 1 method, that will call a "select" function on your Thread.
        Set<String> selected = selector.select(list);
        this.list.remove(selected);
    }

    //after job is done, put the value back in the list, so it's available for another Thread
    public void synchronized releaseValue(Set<String> value) {
        this.list.add(value);
    }
}

当然你可以使用泛型来使这个类更通用