简体   繁体   English

Java同步工具解锁一次即可无限次使用

[英]Java synchronization tool unlock once use unlimited times

I want an object that can be 我想要一个可以

  1. locked once by any thread (no ownership!) 被任何线程锁定一次(无所有权!)

  2. requested an arbitrary number of times resulting in block (block only if locked) 请求任意次数导致块(仅在锁定时块)

  3. unlocked once by any thread (again, no ownership) 由任何线程解锁一次(再次,没有所有权)

  4. all requesting (blocked) threads (including future requests yet to be made!) are no longer blocked 所有正在请求的(被阻止的)线程(包括将来要发出的请求!)都不再被阻止

This seems like it would be akin to a semaphore except with infinite permits once unlocked. 似乎与信号量类似,除了一旦解锁就具有无限许可。

Is this possible in Java? 这在Java中可行吗? How it be accomplished? 如何实现?

Here is the solution I came up with: 这是我想出的解决方案:

public class GateLock {
    private boolean isOpen;
    public GateLock() {
        isOpen = false;
    }

    public synchronized void open(){
        isOpen = true;
        notifyAll();
    }

    public synchronized void close(){
        isOpen = false;
    }

    public synchronized void enter(){
        while(!isOpen) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
    }
}

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

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