JAVA多线程—CompletionService的使用介绍

CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。

好比我同时种了几块地的麦子,然后就等待收割。收割时,则是那块先成熟了,则先去收割哪块麦子。

示例代码:

package syn;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureTest {

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

        ExecutorService service = Executors.newFixedThreadPool(3);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(service);

        for (int i = 0; i < 10; i++) {
            final Integer seq = i + 1;
            completionService.submit(new Callable<Integer>() {

                public Integer call() throws Exception {
                    Thread.sleep((long) (Math.random() * 1000));
                    return seq;
                }
            });
        }

        for (int i = 0; i < 10; i++) {
            Future<Integer> f = completionService.take();
            System.out.println(f.get());
        }
        service.shutdown();
    }

}

运行结果: 
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用线程来读取大文件,以提高读取效率。下面是一个简单的示例代码: ```java import java.io.*; import java.util.concurrent.*; public class MultiThreadedFileReader { private static final int THREAD_POOL_SIZE = 4; // 线程池大小 private static final int BUFFER_SIZE = 1024; // 缓冲区大小 public static void main(String[] args) throws Exception { // 创建线程池 ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); // 打开文件 File file = new File("path/to/large/file"); FileInputStream fis = new FileInputStream(file); // 计算每个线程需要读取的字节数 long fileSize = file.length(); long chunkSize = fileSize / THREAD_POOL_SIZE; if (fileSize % THREAD_POOL_SIZE != 0) { chunkSize++; } // 创建任务 CompletionService<byte[]> completionService = new ExecutorCompletionService<>(executor); for (int i = 0; i < THREAD_POOL_SIZE; i++) { long start = i * chunkSize; long end = Math.min(start + chunkSize, fileSize); completionService.submit(new FileReaderTask(fis, start, end)); } // 等待任务完成并汇总结果 ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < THREAD_POOL_SIZE; i++) { Future<byte[]> future = completionService.take(); baos.write(future.get()); } // 关闭流和线程池 fis.close(); executor.shutdown(); // 输出结果 System.out.println(new String(baos.toByteArray())); } static class FileReaderTask implements Callable<byte[]> { private FileInputStream fis; private long start; private long end; FileReaderTask(FileInputStream fis, long start, long end) { this.fis = fis; this.start = start; this.end = end; } @Override public byte[] call() throws Exception { fis.getChannel().position(start); byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); long bytesRead = 0; while (bytesRead < end - start) { int n = fis.read(buffer); if (n == -1) { break; } baos.write(buffer, 0, n); bytesRead += n; } return baos.toByteArray(); } } } ``` 上述代码中,使用了一个线程池来创建多个任务,每个任务负责读取文件的一部分数据。主线程等待所有任务完成后,将结果合并到一个字节数组中并输出。注意,在任务中需要使用`FileInputStream`的`getChannel()`方法获取文件通道,并在读取文件时使用`position()`方法设置偏移量,以确保每个线程读取的数据不重复。此外,还需要使用`ByteArrayOutputStream`来缓存每个线程读取的数据,并在任务完成后将它们合并到一个字节数组中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值