简体   繁体   中英

Java reader writer

I am a bit stumped on a new concept I am learning in my concepts of programming languages class. Any info would be great. Reader Writer Problem as follows:

This classical problem requires process synchronization for reading and writing. Therefore, you need a synchronization controller before you define and create threads for reading and writing. The following is a controller class (with two methods left out for you to implement). To keep the programming simple, when you write thread classes for reading and writing (say, three readers and one writer), you only need to symbolically print a message when starting reading or writing, and print another message when finishing reading or writing (thus there is no need to create actual shared content each thread reads or writes about).

Here is what I have. I think I am missing something fundamental with threads. Please note that the controller class and methods is given and required, except the startWriting() and stopWriting() must be implemented by me. Thank you.

class Controller {
private int activeReaders = 0;  
private boolean writerPresent = false;  

protected boolean writeCondition() {
    return activeReaders == 0 && !writerPresent;
}

protected boolean readCondition() {
    return !writerPresent;
}

protected synchronized void startRead() {
    while (!readCondition())
        try { wait(); } catch (InterruptedException ex) {}
    ++activeReaders;
}

protected synchronized void stopRead()  { 
    --activeReaders;
    notifyAll();
}

protected synchronized void startWriting(){
    writerPresent = true;
    System.out.println("Writing has begun");
}

protected synchronized void stopWriting(){
    System.out.println("Reading is now available");
    writerPresent = false;      
}

public static void main(String [] args){
    Controller c = new Controller();

    Thread tRead1   = new Thread(new Runnable() {
        @Override
        public void run(){
            c.startRead();
            System.out.println("Reader 1 has started reading");
            c.stopRead();
            System.out.println("Reader 1 has stopped reading");
        }
    });
    Thread tRead2   = new Thread(new Runnable() {
        @Override
        public void run(){
            c.startRead();
            System.out.println("Reader 2 has started reading");
            c.stopRead();
            System.out.println("Reader 2 has stopped reading");
        }
    });
    Thread tRead3   = new Thread(new Runnable() {
        @Override
        public void run(){
            c.startRead();
            System.out.println("Reader 3 has started reading");
            c.stopRead();
            System.out.println("Reader 3 has stopped reading");
        }
    });
    Thread tWrite1  = new Thread(new Runnable() {
        @Override
        public void run(){
            c.startWriting();
            c.stopWriting();

        }
    });

    tRead1.start();
    tRead2.start();
    tWrite1.start();
    try {
        tWrite1.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    tRead3.start();

}

}

First, I recommend you go to the javadocs and read the method definitions for wait, notify, and notifyall. This is the basic waiting / locking / notifying system in Java.

In terms of Readers and Writers, the readers should all be reading from the writer, and put into suspension using wait on the writer if there is no content available. If you have multiple writers, you can do the same thing with the readers waiting on a messagequeue. When the writer writes and has more data to be consumed by a reader, it should call notify on itself (the writer) to wake one consumer up to grab the new data.

And to give you an idea of when you could/should use notifyAll:

Thread.join works by invoking wait on the Thread being joined with. Upon thread death, Thread calls notifyAll to wake up all threads that are waiting for it to finish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM