Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Classical Readers and Writers Problem

Posted on 2004-11-02
14
Medium Priority
?
472 Views
Last Modified: 2012-05-05
Hello all,

I am trying to figure out the Readers/Writers program I made in JAVA.  The problem is, the code I have is deprecated because I am using a very old java book and I want it updated.  Also, I would like to just use one writer instead of multiple writers just to demonstrate.  Can someone help me out in doing this?!  I am rewarding someone 500 points if they can help me out realy fast!!!

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;


public class ReaderWriter{
  public static void main(String[] args){
    new ReadWriteButtons(new ReaderWriter());
  }

  public synchronized void readAccess() throws InterruptedException{
    while(numWriters > 0)
      wait();
    numReaders++;
  }

  public synchronized void writeAccess() throws InterruptedException{
    if (numWriters > 0)
      wait();
    numWriters++;
  }

  public synchronized void doneReading(){
    if(--numReaders == 0)
      notifyAll();
  }

  public synchronized void doneWriting(){
    if(--numWriters == 0)
      notifyAll();
  }

  int numReaders = 0;
  int numWriters = 0;
}

class ReadWriteButtons extends Frame{
  public ReadWriteButtons(ReaderWriter controller){
    theController = controller;
    setTitle("Readers/Writers demo");
    setLayout(new GridLayout(1, 2));
    add(new Button("Read"));
    add(new Button("Write"));
    resize(200, 70);
    show();
  }

  public boolean processEvent(Event evt)
  {
    if (evt.id == Event.WINDOW_DESTROY)
      System.exit(0);
    return super.processEvent(evt);
  }
   
  public boolean action(Event evt, Object arg)
  {
    if(arg.equals("Read")){
      new Reader(theController).start();
      return true;
    } else if(arg.equals("Write")){
      new Writer(theController).start();
      return true;
    } else{
      return super.action(evt, arg);
    }
  }

  ReaderWriter theController;
}

class Reader extends Thread{
  public Reader(ReaderWriter controller){
    id = count++;
    theController = controller;
  }
   
  public void run(){
    System.out.println("Reader number " + id + " arrives");
    try{
      theController.readAccess();
      System.out.println("Reader number " + id + " starts to read");
      sleep((long) (minSleep + Math.random() * (maxSleep - minSleep)));
    } catch(InterruptedException e){
      System.err.println("A reader was interrupted.  Exiting.");
      System.exit(1);
    }
    System.out.println("Reader number " + id + " finishes reading");
    theController.doneReading();
  }
 
  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}

class Writer extends Thread{
  public Writer(ReaderWriter controller){
    id = count++;
    theController = controller;
  }
   
  public void run(){
    System.out.println("Writer number " + id + " arrives");
    try{
      theController.writeAccess();
      System.out.println("Writer number " + id + " starts to write");
      sleep((long) (minSleep + Math.random() * (maxSleep - minSleep)));
    } catch(InterruptedException e){
      System.err.println("A writer was interrupted.  Exiting");
      System.exit(1);
    }
    System.out.println("Writer number " + id + " finishes writing");
    theController.doneWriting();
  }
 
  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}

0
Comment
Question by:djchiena
  • 5
  • 5
  • 4
14 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12476885
package org.prithvi.util;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class ReaderWriter {
  public static void main(String[] args) {
    new ReadWriteButtons(new ReaderWriter());
  }

  public synchronized void readAccess() throws InterruptedException {
    while (numWriters > 0) {
      wait();
    }
    numReaders++;
  }

  public synchronized void writeAccess() throws InterruptedException {
    if (numWriters > 0) {
      wait();
    }
    numWriters++;
  }

  public synchronized void doneReading() {
    if (--numReaders == 0) {
      notifyAll();
    }
  }

  public synchronized void doneWriting() {
    if (--numWriters == 0) {
      notifyAll();
    }
  }

  int numReaders = 0;
  int numWriters = 0;
}

class ReadWriteButtons
    extends Frame {
  public ReadWriteButtons(ReaderWriter controller) {
    theController = controller;
    setTitle("Readers/Writers demo");
    setLayout(new GridLayout(1, 2));
    add(new Button("Read"));
    add(new Button("Write"));
    setSize(200, 70);
    show();
  }

  public boolean processEvent(Event evt) {
    if (evt.id == Event.WINDOW_DESTROY) {
      System.exit(0);
      //  return super.processEvent(evt);
    }
    return false;
  }
 
  public void actionPerformed(ActionEvent ae)
  {
    Button b=(Button)ae.getSource();
    String arg=b.getLabel();
    if (arg.equals("Read")) {
      new Reader(theController).start();
    }
    else if (arg.equals("Write")) {
      new Writer(theController).start();
    }

  }
 

 

  ReaderWriter theController;
}

class Reader
    extends Thread {
  public Reader(ReaderWriter controller) {
    id = count++;
    theController = controller;
  }

  public void run() {
    System.out.println("Reader number " + id + " arrives");
    try {
      theController.readAccess();
      System.out.println("Reader number " + id + " starts to read");
      sleep( (long) (minSleep + Math.random() * (maxSleep - minSleep)));
    }
    catch (InterruptedException e) {
      System.err.println("A reader was interrupted.  Exiting.");
      System.exit(1);
    }
    System.out.println("Reader number " + id + " finishes reading");
    theController.doneReading();
  }

  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}

class Writer
    extends Thread {
  public Writer(ReaderWriter controller) {
    id = count++;
    theController = controller;
  }

  public void run() {
    System.out.println("Writer number " + id + " arrives");
    try {
      theController.writeAccess();
      System.out.println("Writer number " + id + " starts to write");
      sleep( (long) (minSleep + Math.random() * (maxSleep - minSleep)));
    }
    catch (InterruptedException e) {
      System.err.println("A writer was interrupted.  Exiting");
      System.exit(1);
    }
    System.out.println("Writer number " + id + " finishes writing");
    theController.doneWriting();
  }

  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12476980
This code follows singe Reader and Writer

package org.prithvi.util;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class ReaderWriter {
  public static void main(String[] args) {
    new ReadWriteButtons(new ReaderWriter());
  }

  public synchronized void readAccess() throws InterruptedException {
    while (numWriters > 0) {
      wait();
    }
    numReaders++;
  }

  public synchronized void writeAccess() throws InterruptedException {
    if (numWriters > 0) {
      wait();
    }
    numWriters++;
  }

  public synchronized void doneReading() {
    if (--numReaders == 0) {
      notifyAll();
    }
  }

  public synchronized void doneWriting() {
    if (--numWriters == 0) {
      notifyAll();
    }
  }

  int numReaders = 0;
  int numWriters = 0;
}

class ReadWriteButtons
    extends Frame {
  public ReadWriteButtons(ReaderWriter controller) {
    theController = controller;
    initComponents();
    setSize(200, 70);
    show();
  }

  private void initComponents() {
    setTitle("Readers/Writers demo");
    setLayout(new GridLayout(1, 2));
    add(new Button("Read"));
    add(new Button("Write"));

    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        exitForm(evt);
      }
    });

    pack();
  }

  /** Exit the Application */
  private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
  }

  public boolean processEvent(Event evt) {
    if (evt.id == Event.WINDOW_DESTROY) {
      System.exit(0);
      //  return super.processEvent(evt);
    }
    return false;
  }

  public void actionPerformed(ActionEvent ae) {
    Button b = (Button) ae.getSource();
    String arg = b.getLabel();
    if (arg.equals("Read")) {
      new Reader(theController).run();
    }
    else if (arg.equals("Write")) {
      new Writer(theController).run();
    }

  }

  ReaderWriter theController;
}

class Reader
    {
  public Reader(ReaderWriter controller) {
    id = count++;
    theController = controller;
  }

  public void run() {
    System.out.println("Reader number " + id + " arrives");
    try {
      theController.readAccess();
      System.out.println("Reader number " + id + " starts to read");
      Thread.sleep( (long) (minSleep + Math.random() * (maxSleep - minSleep)));
    }
    catch (InterruptedException e) {
      System.err.println("A reader was interrupted.  Exiting.");
      System.exit(1);
    }
    System.out.println("Reader number " + id + " finishes reading");
    theController.doneReading();
  }

  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}

class Writer
     {
  public Writer(ReaderWriter controller) {
    id = count++;
    theController = controller;
  }

  public void run() {
    System.out.println("Writer number " + id + " arrives");
    try {
      theController.writeAccess();
      System.out.println("Writer number " + id + " starts to write");
      Thread.sleep( (long) (minSleep + Math.random() * (maxSleep - minSleep)));
    }
    catch (InterruptedException e) {
      System.err.println("A writer was interrupted.  Exiting");
      System.exit(1);
    }
    System.out.println("Writer number " + id + " finishes writing");
    theController.doneWriting();
  }

  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}
0
 

Author Comment

by:djchiena
ID: 12476986
package org.prithvi.util

What is this import for?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 8

Expert Comment

by:kiranhk
ID: 12477008
import java.awt.AWTEvent;
import java.awt.Button;
import java.awt.Event;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;



public class ReaderWriter{
  public static void main(String[] args){
    new ReadWriteButtons(new ReaderWriter());
  }

  public synchronized void readAccess() throws InterruptedException{
    while(numWriters > 0)
      wait();
    numReaders++;
  }

  public synchronized void writeAccess() throws InterruptedException{
    if (numWriters > 0)
      wait();
    numWriters++;
  }

  public synchronized void doneReading(){
    if(--numReaders == 0)
      notifyAll();
  }

  public synchronized void doneWriting(){
    if(--numWriters == 0)
      notifyAll();
  }

  int numReaders = 0;
  int numWriters = 0;
}

class ReadWriteButtons extends Frame{
  public ReadWriteButtons(ReaderWriter controller){
    theController = controller;
    setTitle("Readers/Writers demo");
    setLayout(new GridLayout(1, 2));
    add(new Button("Read"));
    add(new Button("Write"));
    resize(200, 70);
    this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent evt) {
            // Exit the application
            System.exit(0);
        }
    });

    show();
   
  }

  public void processEvent(AWTEvent evt)
  {
    if ((int)evt.getID() == Event.WINDOW_DESTROY)
      System.exit(0);
   
        super.processEvent(evt);
  }
   
  public boolean action(Event evt, Object arg)
  {
    if(arg.equals("Read")){
      new Reader(theController).start();
      return true;
    } else if(arg.equals("Write")){
      new Writer(theController).start();
      return true;
    } else{
      return super.action(evt, arg);
    }
  }

  ReaderWriter theController;
}

class Reader extends Thread{
  public Reader(ReaderWriter controller){
    id = count++;
    theController = controller;
  }
   
  public void run(){
    System.out.println("Reader number " + id + " arrives");
    try{
      theController.readAccess();
      System.out.println("Reader number " + id + " starts to read");
      sleep((long) (minSleep + Math.random() * (maxSleep - minSleep)));
    } catch(InterruptedException e){
      System.err.println("A reader was interrupted.  Exiting.");
      System.exit(1);
    }
    System.out.println("Reader number " + id + " finishes reading");
    theController.doneReading();
  }
 
  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}

class Writer extends Thread{
  public Writer(ReaderWriter controller){
    id = count++;
    theController = controller;
  }
   
  public void run(){
    System.out.println("Writer number " + id + " arrives");
    try{
      theController.writeAccess();
      System.out.println("Writer number " + id + " starts to write");
      sleep((long) (minSleep + Math.random() * (maxSleep - minSleep)));
    } catch(InterruptedException e){
      System.err.println("A writer was interrupted.  Exiting");
      System.exit(1);
    }
    System.out.println("Writer number " + id + " finishes writing");
    theController.doneWriting();
  }
 
  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}
0
 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 2000 total points
ID: 12477023
This must be your final code




import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class ReaderWriter {
  public static void main(String[] args) {
    new ReadWriteButtons(new ReaderWriter());
  }

  public synchronized void readAccess() throws InterruptedException {
    while (numWriters > 0) {
      wait();
    }
    numReaders++;
  }

  public synchronized void writeAccess() throws InterruptedException {
    if (numWriters > 0) {
      wait();
    }
    numWriters++;
  }

  public synchronized void doneReading() {
    if (--numReaders == 0) {
      notifyAll();
    }
  }

  public synchronized void doneWriting() {
    if (--numWriters == 0) {
      notifyAll();
    }
  }

  int numReaders = 0;
  int numWriters = 0;
}

class ReadWriteButtons
    extends Frame
    implements ActionListener {
  public ReadWriteButtons(ReaderWriter controller) {
    theController = controller;
    initComponents();
    setSize(200, 70);
    show();
  }

  private void initComponents() {
    setTitle("Readers/Writers demo");
    setLayout(new GridLayout(1, 2));
    Button read = new Button("Read");
    Button write = new Button("Write");
    add(read);
    add(write);
    read.addActionListener(this);
    write.addActionListener(this);

    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        exitForm(evt);
      }
    });

    pack();
  }

  /** Exit the Application */
  private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
  }

  public boolean processEvent(Event evt) {
    if (evt.id == Event.WINDOW_DESTROY) {
      System.exit(0);
      //  return super.processEvent(evt);
    }
    return false;
  }

  public void actionPerformed(ActionEvent ae) {
    Button b = (Button) ae.getSource();
    String arg = b.getLabel();
    if (arg.equals("Read")) {
      new Reader(theController).run();
    }
    else if (arg.equals("Write")) {
      new Writer(theController).run();
    }

  }

  ReaderWriter theController;
}

class Reader {
  public Reader(ReaderWriter controller) {
    id = count++;
    theController = controller;
  }

  public void run() {
    System.out.println("Reader number " + id + " arrives");
    try {
      theController.readAccess();
      System.out.println("Reader number " + id + " starts to read");
      Thread.sleep( (long) (minSleep + Math.random() * (maxSleep - minSleep)));
    }
    catch (InterruptedException e) {
      System.err.println("A reader was interrupted.  Exiting.");
      System.exit(1);
    }
    System.out.println("Reader number " + id + " finishes reading");
    theController.doneReading();
  }

  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}

class Writer {
  public Writer(ReaderWriter controller) {
    id = count++;
    theController = controller;
  }

  public void run() {
    System.out.println("Writer number " + id + " arrives");
    try {
      theController.writeAccess();
      System.out.println("Writer number " + id + " starts to write");
      Thread.sleep( (long) (minSleep + Math.random() * (maxSleep - minSleep)));
    }
    catch (InterruptedException e) {
      System.err.println("A writer was interrupted.  Exiting");
      System.exit(1);
    }
    System.out.println("Writer number " + id + " finishes writing");
    theController.doneWriting();
  }

  static int count = 0;
  int id;
  ReaderWriter theController;
  static final int minSleep = 5000; // minimum 1000 ms = 5 second
  static final int maxSleep = 10000; // minimum 5000 ms = 10 seconds
}
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12477056
>> package org.prithvi.util

nothing special abt this. Genreally I do all tests in this package That's it. the last one is your final code
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12477225
comment  Thread.sleep in the code

it is not necessary for your requirement
0
 

Author Comment

by:djchiena
ID: 12477479
I seem to be getting an error when I run the program.  I get

exception in thread "main" java.lang.noClassDefFoundError: ReaderWriter

Any ideas?
0
 
LVL 8

Expert Comment

by:kiranhk
ID: 12477546
did u comment the package??
 package org.prithvi.util


0
 

Author Comment

by:djchiena
ID: 12477598
i took that part out and it's still going crazy on me...weird.
0
 

Author Comment

by:djchiena
ID: 12477646
I will be stepping out and wont be back until 7pm est. I hope whatever you can muster helps.  Thanks alot!
0
 
LVL 8

Expert Comment

by:kiranhk
ID: 12477657
ok, assuming u r running the program from the folder where urReaderWriter class file is
java -classpath . ReaderWriter
0
 
LVL 8

Expert Comment

by:kiranhk
ID: 12477691
0
 

Author Comment

by:djchiena
ID: 12477767
Thanks buddy! i owe you a big one!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month20 days, 17 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question