本文介绍了Java Graphics2d是否可以进行并行绘图操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里做了一点测试以证明问题所在.
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 );
}
}
推荐答案
我从给定的代码中看到,您在单独的作业"线程中执行.每个线程都会创建自己的" BufferedImage并绘制一些内容.
What I seen from given code, that you are execute in threads separate "jobs". Each threads create "his own" BufferedImage and draw something.
因此,关于您的问题:
- 如果要通过并行/并发执行快速绘制,则需要在线程之间共享BufferedImage或Graphics *参考.
这篇关于Java Graphics2d是否可以进行并行绘图操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!