Reputation: 667
I have this code , It is mutual exclusion algorithm
turn = 0 // shared control variable
while (turn != i);
// CS
turn = (turn + 1) % n;
I know how thread works but really I'm little weak in using thread in java so please any suggestion to help me to understand how to convert it in real code using thread of java
sorry for my bad english
Upvotes: 0
Views: 12217
Reputation: 589
this code is not mutually exclusive, consider this execution-
Upvotes: 0
Reputation: 5003
Mutual exclusion is typically achieved, in the simplest form, by marking a method as synchronized. By marking an object's method as synchronized, only one thread can ever execute that object's method at a time. The object owning the method is the monitor.
Additionally, you can define a synchronized block in the code itself, passing it the object to act as the monitor.
I believe you could achieve the same thing in a simpler fashion, by defining a Runnable object which has the logic you want done. Where you want the mutual exclusion, define a synchronized method.
Then that Runnable instance can be passed to as many Threads you need. As they all reference the same Runnable, calls into the synchronized method will be mutually exclusive.
This is not the only way, but it should be what you're after. Hope this helps.
Upvotes: 4