Java线程——线程间通信
来源:互联网 发布:微表情测试软件 编辑:程序博客网 时间:2024/05/14 04:32
因为进程之间不能互访对方的地址空间,在进程之间传替消息只能采用类似于远程调用的手段。这就让多线程之间的通信更加显得有优势。
目录
(1)、传递二进制消息
(2)、传递字符信息
正文
(1)、传递二进制消息
主要用到java.io.PipedOutputStream
拥有允许指定输入管道流的构造方法
和java.io.PipedInputStream
拥有一个指定输出管道流的构造方法。
案例如下:
import java.io.PipedOutputStream;import java.io.PipedInputStream;import java.io.IOException;public class CommunicationByPipeBytes{ static PipedOutputStream pos=null; static PipedInputStream pis=null; public static void main(String[] args) throws IOException { pos=new PipedOutputStream(); pis=new PipedInputStream(pos); Thread thread1=new Thread() { public void run() { try { pos.write("hello".getBytes()); pos.flush(); } catch(IOException ioe) { ioe.printStackTrace(); } } }; thread1.start(); Thread thread2=new Thread() { public void run() { try { byte[] bytes=new byte[pis.available()]; pis.read(bytes,0,bytes.length); System.out.println(new String(bytes)); } catch(IOException ioe) { ioe.printStackTrace(); } } }; thread2.start(); }}
运行结果:
E:\>java CommunicationByPipeByteshello
这个案例实现了二进制信息的传递:线程Thread1通过管道字节流向线程Thread2传递字符“hello”的字节。
(2)、传递字符信息
利用java.io.PipedWriter
拥有指定允许输入管道字符流的构造方法
而java.io.PipedReader
拥有一个指定输出管道字符流的构造方法。
案例如下:
import java.io.PipedWriter;import java.io.PipedReader;import java.io.BufferedWriter;import java.io.BufferedReader;import java.io.IOException;public class CommunicationByPipeCharacters{ static PipedWriter pw=null; static PipedReader pr=null; static BufferedWriter bw=null; static BufferedReader br=null; public static void main(String[] args) throws IOException { pw=new PipedWriter(); pr=new PipedReader(pw); bw=new BufferedWriter(pw); br=new BufferedReader(pr); Thread thread1=new Thread() { public void run() { try { bw.write("hello",0,"hello".length()); bw.newLine(); bw.flush(); } catch(IOException ioe) { ioe.printStackTrace(); } } }; thread1.start(); Thread thread2=new Thread() { public void run() { try { System.out.println(br.readLine()); } catch(IOException ioe) { ioe.printStackTrace(); } } }; thread2.start(); }}
运行结果同上。只是使用的方式有些不一样。
阅读全文