Java Tutorial #11 Using Pipes and Synchronized to read and write data

in java •  7 years ago 

Previous tutorial https://steemit.com/java/@nicetea/java-tutorial-10-using-threads-with-exceptions

In this tutorial, we will create an application that uses a Pipe Class, as well as 2 Threadded classes for reading and writing. So let's get started.

PipeReadThread.java

class PipeReadThread extends Thread {
    private Pipe p;

    public PipeReadThread(Pipe p) {
        this.p = p;
    }

    public void run() {
        p.read();
    }
}

PipeWriteThread.java

class PipeWriteThread extends Thread {
    private Pipe p;

    public PipeWriteThread(Pipe p) {
        this.p = p;
    }

    public void run() {
        p.write(2);
    }
}

In both files, we will declare a new pipe and a standart constructor. The main difference is that the PipeReadThread.java contains a method to read and the PipeWriteThread.java a method to write.

Pipe.java - the main code

class Pipe {
    static final int MAXPIPE = 2;
    private Vector<String> pipevector = new Vector<String>();

    public synchronized void write(int wert) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    System.in));
            for (int i = 0; i < wert; i++) {
                pipevector.add(in.readLine());
            }
            in.close();
        } catch (IOException e) {
        }
        System.out.println("Schreiben ist beendet.");
        System.out.println();
        notify();
    }

    public synchronized void read() {
        while (pipevector.size() == 0)
            try {
                wait();
            } catch (InterruptedException e) {
            }
        int size = pipevector.size();
        for (int i = 0; i < size; i++) {
            System.out.println(pipevector.remove(0));
        }
        notify();
    }
}

Firstly, the attribute pipevector is declared, which is used to store the input data. Also you can see 2 public methods write(int value) and read(). The synchronized keyword is used, so that the threads can see the changes being made. Without them, it could happen, that a reading thread tries to read data, while the writing thread is not yet finished.
If you were following my last tutorials, you will see a lot of code which is similar, besides the pipevector itself. So I will just continue with explaining this one. For all new people, do checkout my last tutorials to fully understand this code!

So inside the write(int value) It will iterate until value. So if value equals to 3, it will iterate exactly 3 times. Inside the for loop, it will read the input from the console and add it to the pipevector with the command pipevector.add();. With notify(); the thread states that it's now finished.

Inside the read() the code

        while (pipevector.size() == 0)
            try {
                wait();
            } catch (InterruptedException e) {
            }

is called. This piece of code makes sure, that the read() function waits until the pipevector is properly being filled.
Inside the for loop, the last added element is being removed and printed out to the screen.

PipeApp.java

public class PipeApp {
    public static void main(String[] args) {
        Pipe p = new Pipe();
        PipeReadThread p1 = new PipeReadThread(p);
        PipeWriteThread p2 = new PipeWriteThread(p);
        p1.start();
        p2.start();
    }
}

Ouput

Selection_049.png

Stay tuned!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Nice post. @nicetea I just Followed you. Please follow me.

Nice post. Followed you. Please follow me.

When it comes to efficiently handling data flow, using pipes and synchronized methods is paramount. Pipes serve as a conduit for seamless communication between processes, allowing data to be transferred smoothly from one end to the other. By employing synchronized methods, we ensure that multiple threads can access shared resources without causing conflicts, creating a harmonious data exchange. Whether it's orchestrating complex data processing tasks or coordinating real-time interactions on a website like https://cosmosartceramics.com, the synergy between pipes and synchronization is invaluable, promoting data integrity and system stability, and ultimately enhancing the user experience.