用JAVA实现的第二类读者写者问题

来源:互联网 发布:员工网络监控 编辑:程序博客网 时间:2024/04/30 18:27
//--Semaphore.java
package rw;public class Semaphore {private int value;//记录希望访问临界资源的线程的计数器个数public Semaphore(int i){this.value=i;}public synchronized void P(){value--;if(value<0)try {wait();} catch (InterruptedException e) {e.printStackTrace();Thread.currentThread().interrupt();}}public synchronized void V(){value++;if(value<=0){notifyAll();}}}

//------------------------------文件2  ReaderWriter.java------------------------------------------------package rw;import java.io.FileNotFoundException;import java.io.PrintStream;public class ReaderWriter extends Thread{String msg;int NO;final int N=100;static public int num=0;static public int readers=0;static public int writers=0;final static public String base="Last Writer:";static public String resource=base+"0";static Semaphore mutexr=new Semaphore(1);static Semaphore mutexw=new Semaphore(1);static Semaphore mutex=new Semaphore(1);static Semaphore mutexWrite=new Semaphore(1);public ReaderWriter(){NO=num++;if(NO%N!=1)    msg="I am reader @"+NO;else msg="I am writer @"+NO;}public void read(){if(writers!=0)//如果有写者,阻塞,并且后续的读者不许进来mutex.P();mutexr.P();readers++;if(readers==1)//保证当读的时候,对写互斥,写者等待mutexWrite.P();mutexr.V();//.............................................读开始...System.out.println("      "+NO+" is reading, resource=" +resource);//.............................................读结束...mutexr.P();readers--;if(readers==0)mutexWrite.V();mutexr.V();if(writers!=0)//如果有写者,阻塞,并且后续的读者不许进来mutex.V();}public void write(){mutexw.P();writers++;if(writers==1)mutex.P();mutexw.V();//.....................................................写开始        mutexWrite.P();resource="base"+NO;System.out.println(NO+" IS WRITING, resource=" +resource);mutexWrite.V();//.....................................................写结束mutexw.P();writers--;if(writers==0)mutex.V();mutexw.V();}public void run(){int n=1000;while(n-->0){if(NO%N!=1){/*try {Thread.sleep(1);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/read();}else {write();/*try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/}}}public static void main(String args[]){PrintStream ps;try {ps = new PrintStream("D:\\readerWriter.txt");System.setOut(ps);} catch (FileNotFoundException e) {e.printStackTrace();}for(int i=0;i<1000;i++){new ReaderWriter().start();}}}

	
				
		
原创粉丝点击