Passing parameters to a function invoked in a separate thread

user3656651 :

Consider the following Java code on Android. I start threads in a for loop. Inside the thread, I am invoking a method with parameters that are changed by the for loop. Are the parameters 'start_index' and 'end_index' passed correctly so that the for loop doesn't change the value of these parameters after the thread is invoked?

for (int i=0; i<chunk_counts*chunk; i+=chunk){

                        final int  start_index=i; //start_index
                        final int end_index = i + chunk; //set end_index

                        new Thread(new Runnable() {
                            public void run() {

                                threadCount.getAndIncrement();
                                ProcessAttendanceAuto(data, start_index, 
end_index);
                            }
                        }).start();


                    }
LppEdd :

These values are effectively final, thus they're thread safe and you don't need to worry about them changing over time. Also, when being passed to the Runnable and when invoking ProcessAttendanceAuto, they're copied.

For example, this

final int startIndex = i;
final int endIndex = i + 1;
new Thread(new Runnable() {
    public void run() {
        final int test = startIndex;
        final int test2 = endIndex;
    }
}).start();

Is translated to

NEW java/lang/Thread
DUP
NEW so/Test$1
DUP
ILOAD 2
ILOAD 3
INVOKESPECIAL so/Test$1.<init> (II)V
INVOKESPECIAL java/lang/Thread.<init> (Ljava/lang/Runnable;)V

Here

INVOKESPECIAL so/Test$1.<init> (II)V

you can see the generated class

class $1 implements Runnable

accepts two int arguments in its constructor.
This means the values startIndex and endIndex are copied.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=109081&siteId=1