开发者

java shared variables

I w开发者_开发知识库as wondering how multiple threads could access the same variable. If the variable is non static and each thread is its own thread object, how can you access the same variable? For instance supposed I have a function that finds the maximum of a 2D array. If each thread finds the maximum of a row, and each thread also maintains a local maximum of that row and compares that local maximum to a shared maximum and updates the shared maximum accordingly, how would you access the shared maximum if you have different thread objects?

For example in this code i have

for(int i=0; i<input.length; i++){
rowArray = input[i];
teste r1 = new teste(rowArray);
runnables.add(r1);
}

this calls the teste class which implements runnable, and instantiates it with a row of the array. Then it adds it to an arraylist of runnables. Now, each teste object has its own variable and reference, so how would you be able to "share" them if you are creating different teste objects for each row? Basically i want to pass by reference instead of value >,>


The threads need to have a way to refer to the same "shared maximum" value in your example.

Two ways of doing that are:

  • have the maximum be a static variable (dubious)

  • pass the "maximum" object as a parameter to your thread when you create it

Note that when multiple threads are accessing the same variable, you must take steps to synchronize access to it (so two threads aren't simultaneously modifying it.

One way to do that is with a synchronized statemtned


Java provides the volatile modifier for variables, which guarantees that each thread will read its current value instead of a thread-cached value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜