java nio 通道之pipe实现

本文通过一个具体的Java NIO Pipe示例,展示了如何利用Pipe在不同线程间进行数据同步。示例中创建了一个Worker线程负责填充ByteBuffer,并写入Pipe;主线程则从Pipe读取数据并打印到标准输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个pipe和linux系统上用来连接两个进程的pipe不是同一概念,

主要是在JVM内部,用来实现不同线程之间的数据同步。

这倒让我想起了go语言的channel技术。



package com.ronsoft.books.nio.channels;

import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;

public class PipeTest {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		WritableByteChannel out = Channels.newChannel(System.out);
		ReadableByteChannel workerChannel = startWorker(10);
		ByteBuffer buffer = ByteBuffer.allocate(100);
		while (workerChannel.read(buffer) >= 0) {
			buffer.flip();
			out.write(buffer);
			buffer.clear();
		}

	}
	
	private static ReadableByteChannel startWorker(int reps) throws Exception {
		Pipe pipe = Pipe.open();
		Worker worker = new Worker(pipe.sink(), reps);
		worker.start();
		return (pipe.source());
	}
	
	private static class Worker extends Thread {
		WritableByteChannel channel;
		private int reps;
		Worker(WritableByteChannel channel, int reps) {
			this.channel = channel;
			this.reps = reps;
		}
		public void run() {
			ByteBuffer buffer = ByteBuffer.allocate(100);
			try {
				for (int i = 0; i < this.reps; i++) {
					doSomeWork(buffer);
					while (channel.write(buffer) > 0) {
						
					}
				}
				this.channel.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} 
	}
	
	private static String [] products = {
			"No good deed ges unpunished",
			"To be, or what?",
			"No matter where you go, there you are",
			"Just say \"Yo\"",
			"My karma ran over my dogma"
	};
	private static Random rand = new Random();
	private static void doSomeWork(ByteBuffer buffer) {
		int product = rand.nextInt(products.length);
		buffer.clear();
		buffer.put(products[product].getBytes());
		buffer.put("\r\n".getBytes());
		buffer.flip();
	}

}


Just say "Yo"
No good deed ges unpunished
To be, or what?
No good deed ges unpunished
To be, or what?
Just say "Yo"
Just say "Yo"
No matter where you go, there you are
No good deed ges unpunished
Just say "Yo"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值