在循环内执行新线程

时间:2019-05-07 12:19:29

标签: java multithreading swing swingworker

我是Java的新手,在阅读文档时,我不清楚如何实现不同的方法。

我有下一个代码:

private ImageIcon scaleImage(int indice, int w, int h, boolean thumbnail) {        
    ImageIcon image = null;
    ImageIO.setUseCache(false);

    if(fileRefernces.get(indice).toLowerCase().endsWith("tif") || fileRefernces.get(indice).toLowerCase().endsWith("tiff")  ) {
        File initialImage = new File(fileRefernces.get(indice));        
        try {
            BufferedImage bImage = ImageIO.read(initialImage);
            image = new ImageIcon(bImage); 
            bImage.flush();
            bImage = null;
        } catch (IOException ex) {
            Logger.getLogger(ImageRender.class.getName()).log(Level.SEVERE, null, ex);
        } 
        initialImage = null;
    } else {
        image = new ImageIcon(fileRefernces.get(indice)); 
    }

    int nw = image.getIconWidth();
    int nh = image.getIconHeight();

    if(nw > w) {
      nw = w;
      nh = (nw * image.getIconHeight()) / image.getIconWidth();
    }

    if(nh > h) {
      nh = h;
      nw = (image.getIconWidth() * nh) / image.getIconHeight();
    }

    System.gc();

    return new ImageIcon(image.getImage().getScaledInstance(nw, nh, Image.SCALE_FAST));
}

代码运行良好,性能低下。要加载很少的图像,需要2到3秒钟,但此刻要加载500或1,000个图像,则需要很多时间。为什么?因为我正在使用主线程获取所有图像。

我的具体情况是下一个,我有一个for循环,我正尝试将它们插入JPanel中。

for(int i = 0; i < fileRefernces.size(); i++) {    

    pageNumber = new JLabel("<html><font color='#003b86'>PÁGINA " + (i + 1) + "</font></html>", JLabel.LEFT);
    pageNumber.setFont(new Font("Calibri", Font.BOLD, 14));
    rightViewer.add(pageNumber);

    JPanelExtended gal = new JPanelExtended();
    gal.setLayout(null);            
    image = new ImageIcon(fileRefernces.get(i));

    imageLabel = new JLabel(scaleImage(i, 100, 120, true), JLabel.LEFT);
    imageLabel.setBounds(5, 5, 100, 120);
    imageLabel.setBorder(BorderFactory.createLineBorder(Color.black));            
    gal.add(imageLabel);

    gal.setBounds(0, 0, 100, 120);
    gal.setBackground(Color.white);

    if(i == 0) {
        gal.setBackground(Color.black);
    }

    gal.index = i;
    rightViewer.add(gal); 
}

有人可以指导我改善代码并在循环内实现ExecutorService或新线程以使我的代码更快?

0 个答案:

没有答案
相关问题