import java.io.*; import java.util.*; /**Class scheduler: implements the synchronized methods, startread, endread, * startwrite and endwrite. * @author Kg2s */ public class scheduler{ private int num_readers, num_writers, resource; public scheduler() { num_readers = 0; num_writers = 0; resource = -1; } /**Waits until the writers, if any, finish using the resource * then increment num_readers and print out the current status *@param thread_id : the current thread id, used in printing the status */ public synchronized void startread(int thread_id){ while(num_writers!=0) { try { wait(); } catch(Exception e){} } num_readers++; String s = String.format("Reader[%d]:(startread) num_readers= %d, num_writers = %d, resource = %d",thread_id,num_readers,num_writers,resource ); System.out.println(s); } /**Decrement num_readers then print out the current status and notify others *that read is complete *@param thread_id : the current thread id, used in printing the status */ public synchronized void endread(int thread_id){ num_readers--; String s = String.format("Reader[%d]:(endread) num_readers= %d, num_writers = %d, resource = %d",thread_id,num_readers,num_writers,resource ); System.out.println(s); notifyAll(); } /**Waits until all the other writers and readers, if any, finish using the resource * then increment num_writers and print out the current status *@param thread_id : the current thread id, used in printing the status */ public synchronized void startwrite(int thread_id){ while(num_writers!=0 || num_readers !=0) { try { wait(); } catch(Exception e){} } num_writers++; resource = thread_id; String s = String.format("Writer[%d]:(startwrite) num_readers= %d, num_writers = %d, resource = %d",thread_id,num_readers,num_writers,resource ); System.out.println(s); } /**Decrement num_writers then print out the current status and notify others *that write is complete *@param thread_id : the current thread id, used in printing the status */ public synchronized void endwrite(int thread_id){ num_writers--; String s = String.format("Writer[%d]:(endwrite) num_readers= %d, num_writers = %d, resource = %d",thread_id,num_readers,num_writers,resource ); System.out.println(s); notifyAll(); } }