piped線程通訊

    一個線程發送數據到輸出管道,另外一個線程從輸入管道中讀取數據。經過使用管道,實現不一樣線程間的通訊,而無須藉助於相似臨時文件之類的東西。
    在java的jdk中提供了4個類來使線程間能夠進行通訊:
        PipedInputStream 和 PipedOutputStream
        PipedReader 和 PipedWriter java

public static class ReadClient implements Runnable{
	private PipedInputStream reader;
	public ReadClient(PipedInputStream reader) {
		this.reader = reader;
	}
	@Override
	public void run() {
		byte[] bytes = new byte[50];
		try {
			do {
				int readLength = reader.read(bytes);//方法會一直阻塞,直到有數據被寫入
				if(readLength==-1){continue;}
				String message = new String(bytes,0,readLength);
				System.out.println("get: "+message);
			}while(true);
		} catch (IOException e) {
			//something 
		}finally{
			try {
				reader.close();
			} catch (IOException e) {
				//something 
			}
		}
	}
}

public static class WriteClient implements Runnable{
	private PipedOutputStream writer;
	public WriteClient(PipedOutputStream writer) {
		this.writer = writer;
	}
	@Override
	public void run() {
		int seed = 0;
		try {
			while (true) {
				seed++;
				String message = ""+seed;
				System.out.println("send: "+seed);
				writer.write(message.getBytes());
				writer.flush();
				Thread.sleep(1000);
			}
		} catch (InterruptedException | IOException e) {
			//something 
		}finally{
			try {
				writer.close();
			} catch (IOException e) {
				//something 
			}
		}
		
	}
	
}

public static void main(String[] args) throws InterruptedException, IOException {
	PipedInputStream inputStream = new PipedInputStream();
	PipedOutputStream outputStream = new PipedOutputStream();
	//管道鏈接
	inputStream.connect(outputStream); //或 outputStream.connect(inputStream);
	//建立讀寫線程
	Thread reader = new Thread(new ReadClient(inputStream));
	reader.start();
	Thread.sleep(2000);
	Thread writer = new Thread(new WriteClient(outputStream));
	writer.start();
	
}

結果:
send: 1
get: 1
send: 2
get: 2
send: 3
get: 3
ide

在main方法中,讀的線程先啓動了,因此在read時會阻塞直到writer線程開始寫數據。若是writer先啓動,數據也不會丟失,會一直寫入到管道中。直到reader線程去讀取它。
相關文章
相關標籤/搜索