package three.day.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamDemo02
{
public static void main(String[] args)
{
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try
{
pos.connect(pis);
(new Producer(pos)).start();
new Customer(pis).start();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
System.out.println("线程间利用管道进行通信");
}
}
}
class Producer extends Thread
{
private PipedOutputStream pos;
public Producer(PipedOutputStream pos)
{
this.pos = pos;
}
public void run()
{
try
{
pos.write("Hello,this is han".getBytes());
pos.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Customer extends Thread
{
private PipedInputStream pis;
public Customer(PipedInputStream pis)
{
this.pis = pis;
}
public void run()
{
int len = 0 ;
byte[] b = new byte[100];
try {
len = pis.read(b);
System.out.println(new String(b,0,len));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamDemo02
{
public static void main(String[] args)
{
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try
{
pos.connect(pis);
(new Producer(pos)).start();
new Customer(pis).start();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
System.out.println("线程间利用管道进行通信");
}
}
}
class Producer extends Thread
{
private PipedOutputStream pos;
public Producer(PipedOutputStream pos)
{
this.pos = pos;
}
public void run()
{
try
{
pos.write("Hello,this is han".getBytes());
pos.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Customer extends Thread
{
private PipedInputStream pis;
public Customer(PipedInputStream pis)
{
this.pis = pis;
}
public void run()
{
int len = 0 ;
byte[] b = new byte[100];
try {
len = pis.read(b);
System.out.println(new String(b,0,len));
} catch (IOException e) {
e.printStackTrace();
}
}
}