gpt4 book ai didi

java - 就运行时性能而言,初始化数千个对象的最有效方法是什么

转载 作者:行者123 更新时间:2023-12-01 04:23:46 24 4
gpt4 key购买 nike

我正在尝试创建一个类的数千个实例,Tile

int length=64;
Tile tiles[][]=new Tile[length][length]
for(int y=0;y<length;y++)for(int x=0;x<length;x++)
try{tiles[x][y]=new Tile(x,y);}catch(FileNotFoundException e) {e.printStackTrace();}

创建新图 block 需要 0.01 到 0.1 秒之间的时间。

我尝试为此创建一个线程,但它使它变慢。

tiles=new Tile[length][length];
private static int y,x;
final CountDownLatch end=new CountDownLatch(length*length);
for( y=0;y<tiles.length;y++)for(x=0;x<tiles.length;x++)
new Thread()
{
public void run()
{
int y=new Integer(OutterClass.y),x=new Integer(OutterClass.x);
try {
tiles[x][y]=new Tile(x,y);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
end.countDown();
}
}.start();
end.await();

有没有办法加快速度?

最佳答案

创建一个线程池(例如,可能通过 ThreadPoolExecutor 获得 Executors.newFixedThreadPool(int) )。将线程数设置为适合您的应用程序和执行环境的值。

循环你的图 block 并 submit一个Runnable对于每个瓷砖。调用submit返回 Future - 将这些放入 List<Future<?> .

循环Future<?>的列表并调用get()在各个。此步骤可确保在继续之前完成所有任务。

关于java - 就运行时性能而言,初始化数千个对象的最有效方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18686037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com