代码共四部分
理论支持,点我点点我
Book类:
/*
* @Author: robot-cmy
* @Date: 2021-11-22 10:59:19
* @Last Modified by: robot-cmy
* @Last Modified time: 2021-11-22 11:54:37
*/
//https://www.cnblogs.com/wkfvawl/p/11538431.html
package myOperationSystem.ReaderAndWriter;
public class Book {
private int[] rw = { 1 }; // 实现对文件的互斥访问,表示当前是否有进程在访问共享文件
private int count = 0; // 记录有几个读进程在访问文件
private int[] mutex = { 1 }; // 保证对count变量的互斥访问
// p操作
public synchronized void P(int[] num) {
num[0]--;
if (num[0] >= 0) {
return;
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// v操作
public synchronized void V(int[] num) {
num[0]++;
if (num[0] > 0) {
return;
} else {
notify();
}
}
// 写者write方法
public void write() {
P(rw);
System.out.println(Thread.currentThread().getName() + " 正在写文件");
V(rw);
System.out.println(Thread.currentThread().getName() + " 写完文件");
}
// 读者read方法
public void read() {
P(mutex);
if (count == 0) {
P(rw);
}
count++;
V(mutex);
System.out.println(Thread.currentThread().getName() + " 读文件");
P(mutex);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
if (count == 0) {
V(rw);
}
V(mutex);
}
}
Reader类:
/*
* @Author: robot-cmy
* @Date: 2021-11-22 11:11:55
* @Last Modified by: robot-cmy
* @Last Modified time: 2021-11-22 11:34:03
*/
package myOperationSystem.ReaderAndWriter;
public class Reader implements Runnable {
private Book book;
public Reader() {
}
public Reader(Book book) {
this.book = book;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
book.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Writer类:
/*
* @Author: robot-cmy
* @Date: 2021-11-22 11:16:14
* @Last Modified by: robot-cmy
* @Last Modified time: 2021-11-22 11:32:00
*/
package myOperationSystem.ReaderAndWriter;
public class Writer implements Runnable {
private Book book;
public Writer() {
}
public Writer(Book book) {
this.book = book;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
book.write();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Main类(主类):
/*
* @Author: robot-cmy
* @Date: 2021-11-22 11:16:17
* @Last Modified by: robot-cmy
* @Last Modified time: 2021-11-22 11:51:50
*/
//https://www.cnblogs.com/wkfvawl/p/11538431.html
package myOperationSystem.ReaderAndWriter;
public class Main {
public static void main(String[] args) {
// 三个读者一个写者
Book book = new Book();
Reader reader1 = new Reader(book);
Reader reader2 = new Reader(book);
Reader reader3 = new Reader(book);
Writer writer = new Writer(book);
Thread r1 = new Thread(reader1, "读者1:");
Thread r2 = new Thread(reader2, "读者2:");
Thread r3 = new Thread(reader3, "读者3:");
Thread w = new Thread(writer, "写者:");
r1.start();
r2.start();
r3.start();
w.start();
}
}