When we use threads thread in Java, in run () {} If we want to pass parameters to the function, generally, the compiling system will prompt us to set this parameter as final as possible, that is, constant, once the definition can no longer be modified.
This is a very good request!
Is it impossible to pass a definition other than final? No, we can get the variables we need to pass to global, but!! The problem is often the way it appears.
Let's look at the following code.
1 for(intu=0;u<result.length;u++){2 Final int Picindex=u;3 Final Bitmap Bitmap=Result[picindex];4 NewThread (NewRunnable () {5 @Override6 Public voidrun () {7 Internethelper.uploadpic8(//To upload a picture in bulk, this static function must be added synchronized9"Http://zzzzzzzz.php?" + "account=" +useraccounttemp+ "&postid=" +Userpostid,Ten Bitmap, //modify it here directly with Result[u] One"" +picindex+ ". jpg"///before modification, Picindex is global A ); - } - }). Start (); the}
This is the real code inside my project, the purpose is to put the bitmap array result inside of the bitmap into a JPG to the server, is to upload pictures, because the picture can not be 1, and larger, about 700K/Zhang, which is already trying to compress the situation, so need to pass multiple threads.
Before the Picindex, bitmap to final, said I met the situation , result always has more than 2 different pictures bitmap data, according to the truth, execute the above code, altogether opened two + threads, Uploaded more than two different pictures.
However, when I detected in the server, I found that I always upload only one picture, that is, I put the same picture, uploaded several times!! Then I started to print the log, respectively, to print U, and bitmap.tostring (), and found that before entering the thread, it was normal, that is, different. According to the truth, I pass the same is different. The Uploadpic function is no problem.
Think, I think it is a thread to make a ghost, it executes the code inside the function, it is too late to execute, for the loop has been completed, then the corresponding parameters will be changed, but the function inside the code to take this number in memory, the back of the time.
Thus, the parameters that will become, to pass, all change to final, problem solving.
No, I can't, I want to record this bug.