[英]Threading in Java. Creating each figure in new thread, loop not working
我想为我创建的每个矩形创建一个单独的线程。 我需要传递参数来运行线程,这是不允许的。 我不知道该怎么做。 这是我已经写的:
int number_of_cubes = 10;
Rect[] r1 = new Rect[number_of_cubes];
for(int i=0; i <number_of_cubes;i++){
Thread myThread = new Thread(new Runnable()
{
public void run(Rect[] r1,int i){
Random rn = new Random();
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
r1[i] = new Rect(rn.nextInt(600), rn.nextInt(400), 15, 15, randomColor);
}
});
}
至于您的直接问题,请使用
final Rect[] r1 = new Rect[number_of_cubes];
for (int i = 0; i < number_of_cubes; i++) {
final int targetIndex = i;
new Thread(new Runnable() { public void run() {
...
r1[targetIndex] = ...
}}).start();
和一些注意事项:
线程创建的开销足够大,只有在您需要大量工作的情况下,这种习惯用法才有意义。 假设至少有10,000个矩形;
您正在冗余地创建两个Random
实例。 每个线程仅使用一个;
注意可见性的问题:你可以使用所有线程都完成后才会矩形阵列( join
从每个线程的main
方法);
仅在中等数量的线程(通常等于可用的CPU内核数量)下,您才能体验到性能提升;
更好的方法是使用执行器服务。
这样做,它将创建一个函数,该函数运行带有参数的所需线程。 然后,在for循环中可以调用它,但是您希望:
nt number_of_cubes = 10;
Rect[] r1 = new Rect[number_of_cubes];
for(int i=0; i <number_of_cubes;i++){
//call the function here if you want
}
public void runThread(final Rect[] r1,final int i){
new Thread(new Runnable(){
@Override
public void run(){
Random rn = new Random();
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
r1[i] = new Rect(rn.nextInt(600), rn.nextInt(400), 15, 15, randomColor);
}
}).start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.