读者写者问题PV操作实现(Java)

本文介绍了一种使用Java实现的读者写者问题解决方案,通过Semaphore信号量控制多个线程(读者和写者)对共享资源的访问,确保了数据的一致性和线程安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值