计算方法每次都不做任何事情,除了初始化(我认为它与线程有关)

时间:2015-11-23 02:10:06

标签: java multithreading swing parallel-processing java-threads

该程序是Mandelbrot设置渲染器,它最初打开时具有正确计算和渲染的图像;这个初始化是用我的recalculate()方法完成的。但是,当我的事件处理程序调用{​​{1}}方法时,我认为它正在跳过不同线程中的所有内容(即它仍然产生控制台输出,但是没有进行繁重的计算)。

我认为这是因为控制台输出显示初始计算的时间通常约为1500~1800 ms,但是对recalculate()的任何进一步调用都会以大约< 15毫秒,GUI更新为纯色。

控制台输出

recalculate()

重新计算()

Working...
Done.
Took 1711 ms.

<event handler calls recalculate()>

Working...
Done.
Took 16 ms.

调用recalculate()

的事件处理程序
public static void recalculate(double x1, double y1, double x2, double y2, int[][] iterCounter){
        MandelbrotTask[] tasks=new MandelbrotTask[4];
        tasks[0]=new MandelbrotTask(maxIters, x1, y1, x2, y2, 0, WIDTH, 0, HEIGHT/4, iterCounter);
        tasks[1]=new MandelbrotTask(maxIters, x1, y1, x2, y2, 0, WIDTH, HEIGHT/4, 2*(HEIGHT/4), iterCounter);
        tasks[2]=new MandelbrotTask(maxIters, x1, y1, x2, y2, 0, WIDTH, 2*(HEIGHT/4), 3*(HEIGHT/4), iterCounter);
        tasks[3]=new MandelbrotTask(maxIters, x1, y1, x2, y2, 0, WIDTH, 3*(HEIGHT/4), 4*(HEIGHT/4), iterCounter);
        //parallelize computation
        Thread[] threads=new Thread[4];
        for(int i=0; i<4; i++){
            threads[i]=new Thread(tasks[i]);
        }

        System.out.println("Working...");
        //start timer, start computation
        long start=System.currentTimeMillis();
        for(int i=0; i<4; i++){
            threads[i].start();
        }

        for(int i=0; i<4; i++){
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                System.err.println("A thread was interrupted.");
            }
        }
        //end timer
        long end=System.currentTimeMillis();
        long elapsed=end-start;
        System.out.println("Done.");
        System.out.println("Took " + elapsed + " ms.");
    }

MandelbrotTask类

protected static void handleMouseReleased(MouseEvent e) {
    recalculate(zoomBox.getX(), zoomBox.getY(), zoomBox.getX()+zoomBox.getWidth(), zoomBox.getY()+zoomBox.getHeight(), iterCounts);
    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run() {
            zoomBox=null;
            bufferedImage=render(iterCounts, bufferedImage, zoomBox);
            ImageIcon icon=new ImageIcon(bufferedImage);
            content.setIcon(icon);
        }
    });
}

0 个答案:

没有答案