开发者

Regarding significance of synchronization

This might be a dumb question to ask but I am new to multi-threaded programming in Java.I created 4 threads and then invoked the run method on them.In the run method I am using an array and am assigning values to it's indices.I see that each thread is maintaining it's own co开发者_如何学Gopy of the array and there is no thread-unsafe behavior. I just wanted to know that in this case what is the significance of using synchronization?(I thought it was used to control access to a shared resource.Isn't the array supposed to be a shared data structure here?)


No -- if each thread uses its own copy of the array, then you have four separate arrays that happen to contain the same data, but no sharing is happening.

Sharing would be if you had one array, and all four threads operated on that array, with at least the potential for two threads to use the same data at the same time. In such a case you would need synchronization to assure that only one of them tried (for example) to write to any specific location at any one time (or that if one was reading and another writing, that the writing was done atomically, with the read happening either completely before the write, or else completely after it -- but the two would not be allowed to overlap).


So long as you are absolutely sure that the arrays are COMPLETELY different (need to be careful here as there can be pointers to the same object depending on what you've done) then you don't need to synchronize the array.


If your threads only perform operations on their own private data, then no synchronization is necessary.

By the way, you say you "invoked the run method" on your threads; calling Thread.run() directly won't execute your logic in a new thread though; you'll want to call Thread.start() instead (which internally executes run() in a separate thread).


It depends what you mean by "In the run method I am using an array " (stress on using)? If you have passed the reference of array to thread then yes, sync will prevent simultaneous access to the array.However, if you create an instance on array in the Thread, then you have 4 separate instance of array and synchronization has no effect.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜