Java中的非重入非阻塞信号量

Kut*_*ach 2 java concurrency semaphore nonblocking

我需要一个具有以下功能的信号量:

  1. 它应该是非阻塞的,即如果线程无法获得许可,它应该更进一步而无需等待
  2. 它应该是非自由的,即如果同一个线程两次进入受保护的代码,它应该带走两个许可而不是一个

我写了以下代码:

public class SimpleSemaphore
{

    private int permits;

    private AtomicLong counter = new AtomicLong();

    SimpleSemaphore(int permits)
    {
        this.permits = permits;
    }

    boolean acquire()
    {

        if (counter.incrementAndGet() < permits)
        {
            return true;
        }
        else
        {
            counter.decrementAndGet();
            return false;
        }

    }

    void release()
    {
        counter.decrementAndGet();

    }
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是这个信号量:

public class EasySemaphore
{

    private int permits;

    private AtomicLong counter = new AtomicLong();

    EasySemaphore(int permits)
    {
        this.permits = permits;
    }

    boolean acquire()
    {
        long index = counter.get();

        if (index < permits)
        {
            if (counter.compareAndSet(index, index + 1))
            {
                return true;
            }
        }

        return false;
    }

    void release()
    {
        counter.decrementAndGet();
    }
}
Run Code Online (Sandbox Code Playgroud)

两个实现都是线程安全且正确的吗?哪一个更好?你会怎么做这个任务?

Thi*_*ilo 7

还没有那么java.util.concurrent.Semaphore做吗?

它具有tryAcquire非阻塞获取,并且它保留了剩余许可的简单计数(其中相同的线程可以取出多于一个).