/* * Rick van der Zwet * 0433373 * Java programming assigment 1.2 * Licence: BSD * $Id: RWProblem.java 270 2007-10-13 13:45:29Z rick $ */ import java.util.Random; class ReadProcess extends Process { public ReadProcess(int number, Database database) { super(number, database); } public void run () { message("Started as READ"); database.get_readlock(); message("Read: " + database.read()); sleep(); database.release_writelock(); message("Ended"); } } class WriteProcess extends Process { public WriteProcess(int number, Database database) { super(number, database); } public void run () { message("Started as WRITE"); database.get_writelock(); database.write(Integer.toString(id)); sleep(); message("Wrote his Id"); database.release_writelock(); message("Ended"); } } class Process extends Thread { protected int id; protected Database database; Process (int number, Database d) { this.id = number; database = d; } protected void sleep () { int sleeptime; sleeptime = (int) (Math.random () * 1000); try { Thread.sleep( sleeptime ); } catch ( InterruptedException e) { } } protected void message (String text) { System.out.println("[" + id + "] " + text); } } public class RWProblem { public static void main (String args[]) { Database database; int N = 100; //processes int i; //loop counter Random write = new Random(); database = new Database(); Process [] process = new Process [N]; for( i = 0; i < N; i++) { if (write.nextBoolean()) { process[i] = new WriteProcess (i, database); } else { process[i] = new ReadProcess (i, database); } process[i].start(); } } }