简体   繁体   中英

Threading in Java. Creating each figure in new thread, loop not working

I want to create a separate thread for each of my created rectangles. I need to pass arguments to run the thread, and it's not allowed. I can't figure out how to do this. This is what I already wrote:

    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);
            }

        });
    }

As for your immediate question, use

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();

And a few notes:

  • the overhead of thread creation is large enough for this idiom to start making sense only if you have a substantial amount of work for it. Say, at least 10,000 rectangles;

  • you are redundantly creating two Random instances. Use just one per thread;

  • watch out for visibility issues: you may use the rectangle array only after all threads have finished ( join on each thread from the main method);

  • you'll experience performance gain only with a moderate number of threads, usually equal to the number of available CPU cores;

  • a much better approach would be to use an Executor Service.

Do this, It will create a function that runs the thread you want with the parameters. Then, in the for loop you can call it however you would like:

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();
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM