# Thread communication through pipes

In 
Published 2024-01-07

This tutorial explains how we can connect threads using pipelines in Java.

The purpose of this example is to show how we can send date from one thread to another.

Please take a look at the example below which is self-explanatory:

First, we need to create a Producer (sends data) and a Consumer (receives data).

MyProducer.java
package com.example.demo;

import java.io.OutputStream;

public class MyProducer extends Thread {

    OutputStream outputStream;

    public MyProducer(OutputStream outputStream)
    {
        this.outputStream = outputStream;
    }

    public void run()
    {

        try{
            outputStream.write(1);
            outputStream.flush();

            Thread.sleep(1000);

            outputStream.write(2);
            outputStream.flush();

            Thread.sleep(1000);

            outputStream.write(3);
            outputStream.flush();
            
        }catch(Exception e) {}
    }
}
package com.example.demo;

import java.io.InputStream;
import java.io.OutputStream;

public class MyConsumer extends Thread {

    InputStream inputStream;

    public MyConsumer(InputStream inputStream)
    {
        this.inputStream = inputStream;
    }

    public void run()
    {
        int count=1;

        String repeat = "Y";
        while(repeat.equals("Y"))
        {
            try{
                int int1= inputStream.read();
                System.out.println("From MyConsumer >> "+int1);

                Thread.sleep(1000);

                int int2= inputStream.read();
                System.out.println("From MyConsumer >> "+int2);

                Thread.sleep(1000);

                int int3= inputStream.read();
                System.out.println("From MyConsumer >> "+int3);

            }catch(Exception e){}
        }
    }
}

And now, in the main class we connect the Consumer and the Producer.

Demo1Application.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.*;

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(Demo1Application.class, args);

        PipedInputStream pipedInputStream = new PipedInputStream();
        PipedOutputStream pipedOutputStream = new PipedOutputStream();

        pipedInputStream.connect(pipedOutputStream);

        MyProducer myProducer = new MyProducer(pipedOutputStream);
        MyConsumer myConsumer = new MyConsumer(pipedInputStream);

        myProducer.start();
        myConsumer.start();
    }
}