发送程序 :
package com.thread;
import java.io.IOException;
import java.io.PipedOutputStream;
public class Thread1 extends Thread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread1(new PipedOutputStream()).start();
}
PipedOutputStream pipeout;
public Thread1(PipedOutputStream pipeout)
{
this.pipeout=pipeout;
}
public void run()
{
while (true)
{
try {
System.out.println(" THis is thread1");
pipeout.write("ABCDEFGHIJKLMNOPQRSTUVWXYZ.".getBytes());
pipeout.flush();
System.out.println("发生数据");
//pipeout.close();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//pipeout.close();
}
}
接收线程:
package com.thread;
import java.io.IOException;
import java.io.PipedInputStream;
public class Thread2 implements Runnable {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new Thread2(new PipedInputStream())).start();
}
PipedInputStream pipein;
Thread2(PipedInputStream pipein)
{
this.pipein=pipein;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true)
{
try {
System.out.println(" THis is thread2");
byte[] bytes = new byte[10];
int length = pipein.read(bytes);
System.out.println("接收:"+new String(bytes,0,length));
//Thread.sleep(10000);
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//主程序
package com.thread;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Multi_Thread {
/**
* @param args
*/
public static void main(String[] args) {
try {
PipedOutputStream pipeout= new PipedOutputStream();
//方式一
//PipedInputStream pipein= new PipedInputStream(pipeout);
//方式二
PipedInputStream pipein= new PipedInputStream();
//方式二1
//pipeout.connect(pipein);
//方式二2
pipein.connect(pipeout);
// TODO Auto-generated method stub
Thread1 threadone=new Thread1( pipeout);
//用Runnable接口类的对象创建线程;
Thread threadtwo=new Thread(new Thread2( pipein));
threadone.start();
threadtwo.start();//strat()方法启动线程;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}