集册 Java实例教程 使用辅助线程测试管道对象。

使用辅助线程测试管道对象。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

559
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用辅助线程测试管道对象。

import java.nio.ByteBuffer;

import java.nio.channels.Channels;//from nowjava

import java.nio.channels.Pipe;

import java.nio.channels.ReadableByteChannel;

import java.nio.channels.WritableByteChannel;

import java.util.Random;


public class Main {

  public static void main(String[] argv) throws Exception {

    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();

    }/**from nowjava.com**/

  }

  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) {

          }

        }


        
展开阅读全文