简体   繁体   中英

Java MultiThreadding Local variables referenced from an inner class must be final of effectively final

I am using multithreadding in a for loop. I am trying to run a method for each thread containing some parameters declared inside the for loop.

I have tried moving the variables to the Thread Body and it works. Apart from variables i and AccuraciesList.

在此处输入图片说明

     for (int i = 0; i < 30; i++) {

        String classifierName = "NaiveBayes";
        String dataFile = "decision_tree_image_dataset";
        String folderName = "dataset2_ff_time";
        String folder = "testFold";

        Instances dataSet = WekaTools.loadData(dataFile + ".arff");

        String path = "Results diagrams/" + folderName + "/" + classifierName;

        new Thread(new Runnable() {

            public void run() {
                try {

                    runThread(classifierName, folder, path, dataFile, i, accuraciesList, dataSet);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

I am still getting the same error no matter what I do. I really need the i to be passed in the function as well as the accuraciesList

i must be either as final or has no value modification after declaration (effectively final).

Since it cannot be final as it is a loop iterator, just copy the value and use that copied final value like this.

final int iVal=i;
new Thread(new Runnable() {

    public void run() {
        try {

            runThread(classifierName, folder, path, dataFile, iVal, accuraciesList, dataSet);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();

This due to the scope of lambda Expression :

The scope of a lambda coincides with the definition of the expression. Therefore, any variables that are in scope at the definition of a lambda expression are in scope for the functional method it represents. This include fields and final or effectively final local variables (non-final local variables whose value doesn't changed after initialization).

Hope that help you

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