//--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 block e.printStackTrace(); } */ read(); } else { write(); /* try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.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(); } } }
用JAVA实现的第二类读者写者问题
最新推荐文章于 2022-01-07 11:50:25 发布