线程间通信
我们所掌握的线程通信手段还只限于主线程通过唤醒,中断机制向子线程发出信号,或者在通过创建子线程时候向构造方法传入数据,以及设置子线程的公有属性。但是仅凭这些事难以胜任要求的。
在多线程开发领域,线程与线程之间需要交换信息。这是一种普遍存在的需求。并不仅限于主线程和子线程之间。子线程和子线程之间也有可能需要交换信息。
线程之间能够方便的基于共享地址空间实现通信,这本身。便是多线程应用程序的一大优势,因为进程之间是不能互访对方的地址空间的。在进程之间传递信息只能采用类似于远程调用的手段。
本文主要讲在线程之间实现二进制信息和字符串的传输。
传递二进制信息
利用java.io.PipedOutputStream和java.io.PipedInputStream可以实现线程之间的二进制信息传输。PipedOutputStream是OutputStream直接子类,而.PipedInputStream是InputStream直接子类。
与OutputStream和InputStream的重要区别在于:PipedOutputStream拥有一个允许指定输入管道流的构造方法,而PipedInputStream拥有一个允许指定输出管道流的构造方法。
下面例子就是线程之间二进制信息传递【CommunicationByPipeBytes】
/** * CommunicationByPipeBytes.java * 版权所有(C) 2011 cuiran2001@163.com * 创建:崔冉 2011-1-13 上午09:06:01 */ package com.cayden.thread731; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; /** * @author 崔冉 * @version 1.0.0 * @desc */ public class CommunicationByPipeBytes { static PipedOutputStream pos=null; static PipedInputStream pis=null; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub pos=new PipedOutputStream(); try { pis=new PipedInputStream(pos); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Thread thread1=new Thread(){ public void run(){ try { pos.write("Hello,Ha ha".getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.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 e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread2.start(); } }
运行结果如下:
Hello,Ha ha
传递字符信息
利用java.io.PipedWriter和java.io.PipedReader在线程之间传输字符信息。与上文的类似。
下面给出一个例子【CommunicationByPipeCharacters】
/** * CommunicationByPipeCharacters.java * 版权所有(C) 2011 cuiran2001@163.com * 创建:崔冉 2011-1-13 上午09:35:10 */ package com.cayden.thread731; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.PipedReader; import java.io.PipedWriter; /** * @author 崔冉 * @version 1.0.0 * @desc */ public class CommunicationByPipeCharacters { static PipedWriter pw=null; static PipedReader pr=null; static BufferedWriter bw=null; static BufferedReader br=null; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub 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 e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread1.start(); Thread thread2=new Thread(){ public void run(){ try { System.out.println(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread2.start(); } }
运行结果如下:
hello