简体   繁体   中英

how to pass the index variable of a for loop to anonymous Thread/Runnable

I've searched for similar questions but they were not involving for-loops. I've got the following code:

    image = new BufferedImage[maxFiles];
    for (int i = 0; i < maxFiles; i++) {
        new Thread(){
            public void run() {                 
                try {
                    file = new File("0" + i + ".jpg");
                    image[i] = ImageIO.read(file);
                } catch (IOException e) {e.printStackTrace();}
            }
        };
    }

As you can see I want to load every image file by its own thread to optimize a bit. Unfortunately the variable i of the for loop can't be passed through the run method and I can't either make it final or static. How would you solve this?

You can have a final variable with the same value.

image = new BufferedImage[maxFiles];
for (int i = 0; i < maxFiles; i++) {
    final int index = i;
    new Thread(){
        public void run() {                 
            try {
                file = new File("0" + index + ".jpg");
                image[index] = ImageIO.read(file);
            } catch (IOException e) {e.printStackTrace();}
        }
    };
}

You probably also want to start your threads.

In addition to @khelwood's solution you can also use instance variables in anonymous classes:

    for (int i = 0; i < maxFiles; i++) {
        new Thread() {
            // Capture i here.
            int index = i;

            public void run() {
                try {
                    file = new File("0" + index + ".jpg");
                    image[index] = ImageIO.read(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
    }

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