執行緒間的協作(3)——管道輸入/輸出流

江左煤郎發表於2018-08-31

1.管道輸入/輸出流類

    分為兩類,位元組流管道類(PipedInputStream/PipedOutputStream)和字元流管道類(PipedReader/ PipedWriter)。這兩個IO流實現了可以在不同的任務中對同一個管道進行讀寫操作,這個模型可以看成是“生產者消-費者模式”的變體,管道是一個阻塞佇列。

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class PipeIO {
	public static void main(String[] args) {
		ReadPipe read=new ReadPipe();
		WritePipe write=new WritePipe();
		ExecutorService exec=Executors.newCachedThreadPool();
		try {
			write.getWriter().connect(read.getRead());;//必須將兩個管道進行連線,然後才可進行執行緒間的資料互動
			exec.execute(read);
			exec.execute(write);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
class ReadPipe implements Runnable{
	PipedReader read=new PipedReader();
	public PipedReader getRead(){
		return  read;
	}
	@Override
	public void run() {
		try {
			while(true){
				System.out.println("read:"+(char)read.read()+";");//當前執行緒從管道讀取資料
			}	
		} catch (IOException e) {
			// TODO: handle exception
		}
	}
}
class WritePipe implements Runnable{
	PipedWriter writer=new PipedWriter();
	public PipedWriter getWriter(){
		return  writer;
	}
	@Override
	public void run() {
		try {
			while(true){
				for(char a=`A`;a<=`z`;a++){
					writer.write(a);//當前執行緒向管道輸出資料
					TimeUnit.SECONDS.sleep(2);
				}
			}	
		} catch (IOException e) {
			// TODO: handle exception
		}catch (InterruptedException e) {
			// TODO: handle exception
		}
	}
}

 


相關文章