集册 Java实例教程 AsynchronousFileChannel和ExecutorService

AsynchronousFileChannel和ExecutorService

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

471
AsynchronousFileChannel和ExecutorService

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousFileChannel;

import java.nio.charset.Charset;

import java.nio.file.Path;
/*
N o w J a v a . c o m - 时代Java
*/

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.ArrayList;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.concurrent.ThreadLocalRandom;


public class Main {

  public static void main(String[] args) {

    final int THREADS = 5;

    ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);

    String encoding = System.getProperty("file.encoding");/**来 自 n o w j a v a . c o m**/

    List<Future<ByteBuffer>> list = new ArrayList<>();

    int sheeps = 0;

    Path path = Paths.get("C:/folder1/", "test.txt");


    Set<StandardOpenOption> options = new HashSet<>();

    options.add(StandardOpenOption.READ);

    

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel

        .open(path, options, taskExecutor)) {

      for (int i = 0; i < 50; i++) {

        Callable<ByteBuffer> worker = new Callable<ByteBuffer>() {

          @Override

          public ByteBuffer call() throws Exception {

            ByteBuffer buffer = ByteBuffer.allocateDirect(ThreadLocalRandom

                .current().nextInt(100, 200));

            asynchronousFileChannel.read(buffer, ThreadLocalRandom.current()

                .nextInt(0, 100));

            return buffer;

          }

        };

        Future<ByteBuffer> future = taskExecutor.submit(worker);

        list.add(future);

      }

      taskExecutor.shutdown();

      while (!taskExec
展开阅读全文