【发布时间】:2012-03-29 15:43:05
【问题描述】:
我发现信号量的简单实现(我的 CustomSemaphore),据我所知,这是“不公平”的,因为进入安全块时只能进入第一个线程(我不确定)。
我怎样才能写出公平的信号量(并发new Semaphore(1, true);的类比)
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
【问题讨论】:
-
这是课程作业吗?如果是,请添加作业标签。
标签: java concurrency semaphore