[英]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.