Я нашел простую реализацию семафора (мой CustomSemaphore) и, как я понимаю, это «нечестно», потому что в защищенный блок все время может войти только первый поток (я не уверен).
Как я могу написать честный семафор (аналог параллелизма новый семафор (1, правда);
)
public class SimpleSemaphoreSample2 {
CustomSemaphore cSem = new CustomSemaphore(1);
public static void main(String[] args) {
SimpleSemaphoreSample2 main = new SimpleSemaphoreSample2();
Semaphore sem = new Semaphore(1, true);
Thread thrdA = new Thread(main.new SyncOutput(sem, "Thread1"), "Thread1");
Thread thrdB = new Thread(main.new SyncOutput(sem, "Thread2"), "Thread2");
thrdA.start();
thrdB.start();
try {
thrdB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("END");
}
class SyncOutput implements Runnable {
private Semaphore sem;
private String msg;
public SyncOutput(Semaphore s, String m) {
sem = s;
msg = m;
}
@Override
public void run() {
while (true) {
try {
// sem.acquire();
cSem.acquire();
System.out.println("Before");
Thread.sleep(500);
System.out.println(msg);
Thread.sleep(500);
System.out.println("After");
Thread.sleep(500);
} catch (Exception exc) {
exc.printStackTrace();
}
// sem.release();
cSem.release();
}
}
}
public class CustomSemaphore {
private int counter;
public CustomSemaphore() {
this(0);
}
public CustomSemaphore(int i) {
if (i < 0)
throw new IllegalArgumentException(i + " < 0");
counter = i;
}
public synchronized void release() {
if (counter == 0) {
this.notify();
}
counter++;
}
public synchronized void acquire() throws InterruptedException {
while (counter == 0) {
this.wait();
}
counter--;
}
}
}
enter code here