Kut*_*ach 2 java concurrency semaphore nonblocking
我需要一个具有以下功能的信号量:
我写了以下代码:
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)
两个实现都是线程安全且正确的吗?哪一个更好?你会怎么做这个任务?
| 归档时间: |
|
| 查看次数: |
2003 次 |
| 最近记录: |