Are parallel drawing operations possible with Java

2019-07-20 19:00发布

问题:

I've a little test here to demonstrate the problem.

Obviously the code works but as you increase the thread count (assuming there are enough cores) performance does not improve.

It's as if drawing operations are serialised.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Random;

public class Para2dTest {

class DrawSomething implements Runnable {

    @Override
    public void run() {

        Random r = new Random();

        long start = new Date().getTime();

        BufferedImage image = new BufferedImage( 100, 100, BufferedImage.TYPE_INT_ARGB );
        Graphics2D g2d = image.createGraphics();
        for ( int i = 0; i < 100000; i++ ) {
            Color c = new Color( r.nextInt(256), r.nextInt(256), r.nextInt(256) );
            g2d.setPaint(c);
            g2d.fillRect( 0, 0, 100, 100 );
        }
        g2d.dispose();

        long end = new Date().getTime();

        System.out.println( Thread.currentThread().getName() + " " + ( end - start ) );
    }
}

public Para2dTest( int threads ) {

    for ( int t = 0; t < threads; t++ ) {
        Thread ds = new Thread( new DrawSomething() );
        ds.start();
    }
}

public static void main(String[] args) {

    System.setProperty("java.awt.headless", "true");

    int threads = 16;
    if (args.length > 0) {
        try {
            threads = Integer.parseInt(args[0]);
            System.out.println("Processing with " + threads + " threads");
        } catch (NumberFormatException e) {
            System.err.println("Argument" + " must be an integer");
        }
    }

    new Para2dTest( threads );
}
}

回答1:

What I seen from given code, that you are execute in threads separate "jobs". Each threads create "his own" BufferedImage and draw something.

So, regarding your question:

  • if you want to draw quickly by paralleling/concurrent execution, you will need to share BufferedImage or Graphics* reference between threads.