我在这里做了一个小测试来演示这个问题。
显然,代码可以工作,但是当您增加线程数(假设有足够的核心)时,性能不会提高。
就好像绘图操作是序列化的。
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 );
}
}
最佳答案
我从给定的代码中看到,您是在单独的“作业”线程中执行的。每个线程创建“他自己的”BufferedImage 并绘制一些东西。
所以,关于你的问题:
- 如果您想通过并行/并发执行来快速绘制,您将需要在线程之间共享 BufferedImage 或 Graphics* 引用。
关于java - Java Graphics2d 可以进行并行绘图操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956157/