import java.util.Scanner;
//读者写者问题
public class Test {
public static void main(String[] args) {
int wr, re;
Scanner input = new Scanner(System.in);
System.out.print("请输入写者数目:");
wr = input.nextInt();
System.out.print("请输入读者数目:");
re = input.nextInt();
input.close();
// 实例化读者与写者对象
for (int i = 0; i < wr; i++) {
new Thread(new Writer(), "写者线程r" + Integer.toString(i))
.start();
}
for (int i = 0; i < re; i++) {
new Thread(new Reader(), "读者线程r" + Integer.toString(i))
.start();
}
}
}
//读者
class Reader implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
Global.naps();
System.out.println(Thread.currentThread().getName() + " 等待...");
Global.R_mutex.P();
if (Global.RC == 0) {
Global.RW_mutex.P();
}
Global.RC++;
Global.R_mutex.V();
System.out.println(Thread.currentThread().getName() + " 开始读...");
Global.naps();
System.out.println(Thread.currentThread().getName() + " 离开...");
Global.R_mutex.P();
Global.RC--;
if (Global.RC == 0) {
Global.RW_mutex.V();
}
Global.R_mutex.V();
}
}
//写者
class Writer implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
Global.naps();
System.out.println(Thread.currentThread().getName() + " 等待...");
Global.RW_mutex.P();
System.out.println(Thread.currentThread().getName() + " 开始写...");
Global.naps();
System.out.println(Thread.currentThread().getName() + " 离开...");
Global.RW_mutex.V();
}
}
//全局对象
class Global {
public static Semaphore RW_mutex = new Semaphore(1); //写者与其他写者或读者互斥的访问共享数据
public static Semaphore R_mutex = new Semaphore(1); //读者互斥的访问读者计数器
public static int RC = 0; //对读者进行计数
//随机等待
public static void naps() {
try {
Thread.sleep((int) (2000 * Math.random()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//信号量
class Semaphore {
public int value;
public Semaphore(int value) {
super();
this.value = value;
}
//P操作
public synchronized final void P() {
// TODO Auto-generated method stub
value--;
if(value < 0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//V操作
public synchronized final void V() {
// TODO Auto-generated method stub
value++;
if (value <= 0) {
this.notify();
}
}
}