public class SemaphoreWithQueues implements Semaphore {
private List<Object> queue;
private AtomicInteger current = new AtomicInteger(0);
private int permits;
public SemaphoreWithQueues(int permits) {
this.permits = permits;
this.queue = Collections.synchronizedList(new LinkedList<>());
}
@Override
public void enter() throws InterruptedException {
if (current.get() < permits) {
current.incrementAndGet();
} else {
Object block = new Object();
synchronized (block) {
queue.add(block);
block.wait();
current.incrementAndGet();
}
}
}
@Override
public void leave() {
if(queue.size() != 0) {
Object block = queue.get(0);
queue.remove(0);
synchronized (block) {
block.notify(); //Unblock quenue
}
}
current.decrementAndGet();
//current lessen and current thread have time come in block if(...)
// in enter() faster then another thread increased current
}
}
> The program usually output:
>
> 1 1 2 2 1 1 2 2 1 2
**Where run() of both threads is almost the same, such as:**
public void run(){
for (int i = 0; i <5; i++) {
try {
semaphore.enter();
} catch (InterruptedException e) {
System.err.println(e);
}
System.out.println(2);
semaphore.leave();
}
}
このセマフォを使用するスレッドは2つあります。 1つのスレッドがキューが増加すると、第二が待っている、問題は、我々はqueneとブロックされていないからオブジェクトを抽出した場合、それは、休暇を()終了後、スレッドはより速く、再び)(が入り始めるということですカウンタをに増やし、awakeスレッドはカウンタを,現在= 2とインクリメントし、リストは空です。キューを持つセマフォ
BAD ENGLISH FOR SORRY
'if(current
intをAtomicIntegerに変更しましたが、これで問題は解決しませんでした。 – Youlfey
'AtomicInteger'は、別のスレッドが比較' current