`

jdk6.0从入门到精通-----chapter7线程(2)通信

阅读更多
  线程通信利用java IO中的内部管道(Pipe),可以实现字节,字符信息的传输
二进制信息传输
package communication;

//线程通信,实现二进制传输
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();
	}
}


字符传输

package communication;

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();
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics