我在这里做了一点测试来证明这个问题。
显然代码可以工作但是当你增加线程数时(假设有足够的内核),性能没有提高。
就像绘制操作被序列化一样。
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 );
}
}
答案 0 :(得分:0)
我从给定的代码中看到,您在线程中执行单独的“作业”。每个线程创建“他自己的”BufferedImage并绘制一些东西。
所以,关于你的问题: