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