import java.io.*;
import java.util.*;
public class os
{
public static void main(String args[])
{
Database d= new Database();
d.napping();
Writer w1= new Writer(d);
w1.start();
Reader r1= new Reader(d);
r1.start();
}
}
class Database{
private static final int NAP_TIME=5;
private int readercount;
private boolean dbreading;
private boolean dbwriting;
private File afile;
public Database()
{
readercount=0;
dbreading= false;
dbwriting= false;
afile= new File("test.txt");
}
public static void napping()
{
int sleepTime= (int)(NAP_TIME*Math.random());
try{
Thread.sleep(sleepTime*1000);
}
catch(InterruptedException e){ }
}
public synchronized int startread()
{
while(dbwriting==true)
{
try{
wait();
}
catch(InterruptedException e){ }
}
++readercount;
if(readercount==1)
dbreading= true;
try{
FileInputStream fin= new FileInputStream(afile);
byte buf[]= new byte[10];
fin.read(buf);
System.out.println("Thread Reader reading now(printout)");
System.out.println(new String(buf,0,10));
fin.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException exp)
{
exp.printStackTrace();
}
return readercount;
}
public synchronized int endread()
{
--readercount;
if(readercount==0)
dbreading= false;
System.out.println("End reading\n");
notifyAll();
return readercount;
}
public synchronized void startwrite()
{
while(dbreading== true||dbwriting== true)
{
try{
wait();
}
catch(InterruptedException e){ }
}
dbwriting= true;
try{
String[] source= {"honghejinji ","tianlei ","recursion "};
Random tian=new Random();
int mm=tian.nextInt(3);
byte buf[]= source[mm].getBytes();
FileOutputStream fout= new FileOutputStream(afile);
System.out.println("Thread Writer writing now");
fout.write(buf);
fout.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException exp)
{
exp.printStackTrace();
}
}
public synchronized void endwrite()
{
dbwriting= false;
System.out.println("End writing\n");
notifyAll();
}
}
class Reader extends Thread
{
private boolean done=false;
private Database d;
Reader(Database d)
{
this.d= d;
}
synchronized boolean ok()
{
return(!done);
}
public void run()
{
while(ok())
{
d.startread();
d.endread();
try{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Writer extends Thread
{
private boolean done=false;
private Database d;
Writer(Database d)
{
this.d= d;
}
synchronized boolean ok()
{
return(!done);
}
public void run()
{
while(ok())
{
d.startwrite();
d.endwrite();
try{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}