线程池多线程处理任务

ExecutorService executor = Executors.newFixedThreadPool(Integer.valueOf(7));
try {
    for(File file : files) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                construct(file, length);
            }
        });
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(null != executor) {
        executor.shutdown();
    }
}

其中线程个数取CPU核数+1

@Component
public class PostConstruct {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    int twoI = 0;
    int threeI = 0;
    @Value("${oldPath}")
    private String oldPath;
    @Value("${newDisk}")
    private String newDisk;
    @Value("${cpus}")
    private String cpus;
    @javax.annotation.PostConstruct
    public void test() {
        List<File> files = new ArrayList<>();
        files = traverseFolder(oldPath,files);
        int length = files.size();
        System.out.println("总共"+length+"文件");
        if(!CollectionUtils.isEmpty(files)) {
            ExecutorService executor = Executors.newFixedThreadPool(Integer.valueOf(cpus));
            try {
                for(File file : files) {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            construct(file, length);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(null != executor) {
                    executor.shutdown();
                }
            }
        }
    }

    public void construct(File file,Integer length){
        String path = file.getAbsolutePath();
        try (ImageInputStream iis = ImageIO.createImageInputStream(new File(path))) {
            Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
            if (!it.hasNext()) {
                System.out.println("Can't get ImageReaders");
                return ;
            }
            ImageReader reader = it.next();
            reader.setInput(iis);
            IIOMetadata metadata = reader.getImageMetadata(0);
            IIOMetadataNode rootNode = (IIOMetadataNode) metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            int xDpi = -1;
            // 横DPI取得
            NodeList nodes = rootNode.getElementsByTagName("HorizontalPixelSize");
            if (nodes.getLength() > 0) {
                IIOMetadataNode node = (IIOMetadataNode) nodes.item(0);
                NamedNodeMap nodeAttrs = node.getAttributes();
                Node attr = nodeAttrs.item(0);
                xDpi = Math.round(25.4f / Float.parseFloat(attr.getNodeValue()));
            }
            if (xDpi == 300) {
                String newImage = newDisk + path.substring(1, path.length());
                File newImageFile = new File(newImage);
                String absolutePath = newImageFile.getParent();
                boolean directory = new File(absolutePath).isDirectory();
                if (!directory) {
                    new File(absolutePath).mkdirs();
                }
                imageCopy(path, newImage);
                Thumbnails.of(new File(path))
                        .size(1654, 2338)
                        .outputQuality(1)
                        .toFile(new File(path));
                handleDpi(new File(path), 200, 200);
                threeI++;
            } else {
                twoI++;
            }
            System.out.println(fmt.format(new Date())+":"+Thread.currentThread().getName()+":200dpi:" + twoI + "/" + length + ";300dpi:" + threeI + "/" + length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 遍历目录
     * @param path
     * @param fileList
     * @return
     */
    public static List<File> traverseFolder(String path,List<File> fileList) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                return fileList;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        traverseFolder(file2.getAbsolutePath(),fileList);
                    } else {
                        fileList.add(file2);
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        return fileList;
    }

    /**
     * 拷贝图片
     * @param oldImage
     * @param newImage
     */
    public static void imageCopy(String oldImage, String newImage) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(oldImage);
            //创建文件输出流对象读取指定目录下的文件
            out = new FileOutputStream(newImage);
            //定义一个int类型的变量length
            int length = 0;
            byte[] buff=new byte[1024];
            //获取文件拷贝的时间
            //通过循环将读取到的文件字节信息写入到新文件
            while ((length = in.read(buff)) != -1) {
                out.write(buff,0,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != out){
                    out.flush();
                    out.close();
                }
                //关闭流
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 压缩图片
     * @param file
     * @param xDensity
     * @param yDensity
     */
    public static void handleDpi(File file, int xDensity, int yDensity) {
        FileOutputStream fileOutputStream = null;
        try {
            BufferedImage image = ImageIO.read(file);
            fileOutputStream = new FileOutputStream(file);
            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
            JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
            jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
            jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
            jpegEncodeParam.setQuality(0.75f, false);
            jpegEncodeParam.setXDensity(xDensity);
            jpegEncodeParam.setYDensity(yDensity);
            jpegEncoder.encode(image, jpegEncodeParam);
            image.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,使用线程池可以方便地开启多线程处理任务Java提供了几种常见的线程池创建方式,其中推荐使用ThreadPoolExecutor的构造器来创建适合业务场景的线程池。\[1\] 常见的线程池创建方式包括: 1. FixedThreadPool(固定线程池):线程池的大小一旦达到固定数量就会保持不变,适用于需要控制并发线程数量的场景。 2. SingleThreadExecutor(单线程化的线程池):只有一个线程的线程池任务按照提交的次序顺序执行,适用于需要按顺序执行任务的场景。 3. CachedThreadPool(可缓存线程池):线程池的大小可以根据需要自动调整,适用于需要处理大量短期任务的场景。 使用线程池的好处是可以提前创建好多个线程,放入线程池中,使用时直接获取,使用完后放回池中,避免频繁创建和销毁线程,实现线程的重复利用。线程池能够独立负责线程的创建、维护和分配,提高了线程的执行效率和资源利用率。\[2\]\[3\] #### 引用[.reference_title] - *1* *2* *3* [java多线程(线程池)使用总结](https://blog.csdn.net/domine/article/details/127342754)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值