实验存档。
允许好几个人同时读,但是不允许在有人读的时候写,以及同一时间只能有一个人在写。
读者.java:
package operating.entity.readerwriter; import operating.method.Semaphore; public class Reader implements Runnable {
private static int total = 0;
private int id;
private Semaphore rmutex, wmutex;
private static int readCount = 0; public Reader(Semaphore rmutex, Semaphore wmutex) {
id = ++total;
this.rmutex = rmutex;
this.wmutex = wmutex;
} @Override
public void run() {
while (true) {
rmutex.p();
// 只有第一个读者进程需要执行 wmutex.p()
if (readCount == 0) wmutex.p();
readCount++;
rmutex.v(); // 执行读操作
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
} rmutex.p();
readCount--;
System.out.println(id + " 号读者结束阅读:当前还剩 " + readCount + " 位读者在读");
if (readCount == 0) wmutex.v();
rmutex.v();
}
}
}
写者.java:
package operating.entity.readerwriter; import operating.method.Semaphore; public class Writer implements Runnable {
private static int total = 0;
private int id;
private Semaphore wmutex; public Writer(Semaphore wmutex) {
id = ++total;
this.wmutex = wmutex;
} @Override
public void run() {
while (true) {
wmutex.p();
// 执行写操作
System.out.println(id + " 号写者正在写"); wmutex.v();
}
}
}
主函数.java:
package operating.test; import operating.entity.readerwriter.Reader;
import operating.entity.readerwriter.Writer;
import operating.method.Semaphore; public class ReaderWriterTest {
public static void main(String[] args) {
// 实现写者与写者间、读者与写者间互斥
Semaphore wmutex = new Semaphore(1);
// 用于改变 readCount 变量时实现互斥
Semaphore rmutex = new Semaphore(1); for (int i = 0; i != 5; ++i) {
new Thread(new Writer(wmutex)).start();
new Thread(new Reader(rmutex, wmutex)).start();
}
}
}
/