Function variables values are shared in multi thread?
Below is the example code
Class Abc {
void method1(){
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for(int i=0;i<100;i++){
threadPool.execute(new Runnable() {
doSomeThing(Param);
});
}
threadPool.shutdown();
}
void doSomeThing(Param param){
Object ref1,ref2,ref3,ref4;
}
}
Here we execute the method doSomeThing() in multithread. And doSomeThing() method has many object references.
My question is if any thread changes the state of object reference will this 开发者_运维问答change is visible to other thread?
If so what i need to do to make the thread to have its own state. I know we can fix this by creating a new instance of class while passing it in execute(). I am trying to fix the problem with this style
Each call to doSomeThing
will get its own set of variables, whether they're in the same thread or not.
The variables will be equal to whatever you set them to in each call.
My question is if any thread changes the state of object reference will this change is visible to other thread?
And the simple answer is yes. However, this is far too simple to be helpful.
What you are asking is fundamental to the multithreading concept. Essentially, if you pass the same object to several threads at once then either the changes each thread makes to the object must be choreographed carefully or you must live with unpredictable results.
精彩评论