简体   繁体   English

如何避免从具有相同参数的多个线程执行方法?

[英]How to avoid method execution from multiple threads with same parameter?

How to avoid method execution from multiple threads if they pass same parameter. 如果多个线程传递相同的参数,如何避免方法执行。 for example I have this method: 例如,我有这种方法:

public void sync(int x){    

    //sync code -> write code here which is eligible for sync
}

If this method is running with parameter x=5 and another request with same value x=5 comes, it should be added in queue. 如果此方法使用参数x=5运行,并且另一个请求具有相同的值x=5 ,则应将其添加到队列中。

You can use name-based lock . 您可以使用基于名称的lock

public void sync(int x){
    Lock lock = new NameBasedLock(String.valueOf(x));
    lock.lock();
    try {
        doSomething();
    } finally {
        lock.unlock();
    }
}

You can use simply 您可以简单地使用

   public synchronized void sync(int x){
       //Body of method

} }

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

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