package cn.Douzi.ReadWriter;
import java.util.Scanner;
public class ReadWrite {
static public int count = 0; //读者数量
static public int wcnt = 0; //写者数量
static public int REATIME = 1500; //读者休眠时间
static public int WRITIME = 1000; //写者休眠时间
static public boolean wFlag = false; //写信号 - 用于实现写优先
static public boolean rFlag = false; //读信号
static public Mutex mutex = new Mutex(1); //用于保护更新count变量时的互斥
static public Mutex rw = new Mutex(1); //用于保证读者和写者互斥的访问文件
static public StringBuilder file = new StringBuilder("空");
public static void main(String[] args) {
System.out.println("|-----------------------------------------------------------|");
System.out.println("| |");
System.out.println("| Welcome to My System ! |");
System.out.println("| ↖ By Douzi 2017 ↗ |");
System.out.println("| 读写程序开始进行 |");
System.out.println("| |");
System.out.println("|-----------------------------------------------------------|");
Scanner scaner = new Scanner(System.in);
System.out.println("设置读进程休眠时间: ");
REATIME = scaner.nextInt();
System.out.println("设置写进程休眠时间: ");
WRITIME = scaner.nextInt();
Writer w = new Writer();
Reader r = new Reader();
Thread t1 = new Thread(w);
Thread t2 = new Thread(r);
t1.start(); t2.start();
}
}
class Writer implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(ReadWrite.WRITIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!ReadWrite.wFlag && !ReadWrite.rFlag) { //在无写进程请求时进入
synchronized (ReadWrite.rw) { //互斥访问共享文件
System.out.println("写文件..........."); //写入
System.out.println("文件:" + ReadWrite.wcnt + "
");
ReadWrite.file.append("文件:" + ReadWrite.wcnt++ + " - ");
if (ReadWrite.wcnt % 5 == 0) {
ReadWrite.file.append("
");
}
}
} else {
break;
}
}
}
}
class Reader implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(ReadWrite.REATIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!ReadWrite.wFlag) { //在无写进程请求时进入
synchronized (ReadWrite.mutex) { //互斥访问count变量
if (ReadWrite.count == 0) { //当第一个读进程读共享文件时
ReadWrite.rFlag = true;
}
ReadWrite.count++; //读者计数器
System.out.println("读者数:" + ReadWrite.count );
}
} else {
System.out.println("已有写进程,暂不读文件............
");
break;
}
System.out.println("读文件: " + ReadWrite.file + "
");
synchronized (ReadWrite.mutex) { //互斥访问count变量
ReadWrite.count--; //读者计数器减1, 只有读者=0时候,才能继续写
if (ReadWrite.count == 0) { //当最后一个读进程读完共享文件
ReadWrite.rFlag = false;
}
}
}
}
}
class Data {
private int data;
public Data(int data) {
super();
this.data = data;
}
public int getData() {
return data;
}
}
class Mutex {
private int mutex;
public Mutex(int mutex) {
super();
this.mutex = mutex;
}
}
class Buffer {
private int full;
private int empty;
public Buffer(int full, int empty) {
super();
this.full = full;
this.empty = empty;
}
}