简体   繁体   English

一次只允许一个线程使用一个对象

[英]Allow only one thread at the time to use an object

I have the following class: 我有以下课程:

public class MyClass{

    private List<Integer> ints = new LinkedList<Integer>();

    public List<Integer> getInts(){
        return ints;
    }

    public synchronized void doAction(){ 
        //Do some with the list
    }
}

I need to allow only one thread at the time having acces to the List . 我只需要允许一个线程同时访问List I would do that as follows: 我将按照以下方式进行操作:

public class MyClass{

    private List<Integer> ints = new LinkedList<Integer>();
    private static final Semaphore s = new Semaphore(1);

    public List<Integer> getInts(){
        s.acquire();
        return ints;
    }

    public void release(){
        s.release();
    }

    public synchronized void doAction(){ 
        s.acquire();
        //Do some with the list
        s.release();
    }
}

But the implementaion is obviously not reliable, because if the client request the List through the getter for adding some elements into it and forget to call release() we'll get into troubles if try to invoke the doAction method. 但是实现显然是不可靠的,因为如果客户端通过getter请求List来向其中添加一些元素,而忘记了调用release()那么如果尝试调用doAction方法会遇到麻烦。

What is the solution for the problem? 该问题的解决方案是什么?

Don't allow the client to get the reference. 不允许客户获取参考。 Put all the methods that work on the list to MyClass and synchronize them. 将列表上MyClass所有方法放入MyClass并进行同步。

You can allow the users to get a snapshot copy of the list however. 但是,您可以允许用户获取列表的快照副本。

您可以使用同步列表:

private List<Integer> ints = Collections.synchronizedList(new LinkedList<Integer>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM