import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.atomic. AtomicBoolean;
public class MyPipedStream1 {
public static void main(String[] args) {
try {
final PipedOutputStream p1 = new PipedOutputStream();
final PipedInputStream p2 = new PipedInputStream(p1);
final AtomicBoolean b1 = new AtomicBoolean(false);
final AtomicBoolean b2 = new AtomicBoolean(false);
final DataOutputStream dout = new DataOutputStream(p1);
final DataInputStream din = new DataInputStream(p2);
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
boolean exit = false;
while (exit == false) {
try {
while (!b1.get()) {
synchronized (b1) {
try {
System.out.println("Waiting for Thread 1 to send Data");
b1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("Exited waiting state");
System.out.println("Reading:" + din.readInt());
synchronized (b2) {
b2.set(true);
b2.notify();
}
synchronized (b1) {
b1.set(false);
}
} catch (IOException e) {
System.out.println("Exited the loop");
exit = true;
}
System.out.println("---------- ---End of loop in Thread 2-----------");
}
}
}, "Thread 2");
t2.start();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("Writing:" + i);
dout.writeInt(i);
synchronized (b1) {
b1.set(true);
b1.notify();
}
while (!b2.get()) {
synchronized (b2) {
try {
System.out.println("Waiting for Thread 2 to rx data");
b2.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
synchronized (b2) {
b2.set(false);
}
System.out.println("---------- ---End of loop in Thread 1-----------");
}
synchronized (b1) {
b1.set(true);
b1.notify();
}
}
}, "Thread 1");
t1.start();
} catch (IOException e) {
}
}
}