| Author |
Threading and synchronization
|
Ken Teoh
Greenhorn
Joined: Jul 20, 2006
Posts: 18
|
|
Hi guys, I have a quiz question I hope you guys can understand public class OrderedThread { public static void main(String[] args) { MBThread first,second,third; OrderedThread orderedThread = new OrderedThread(); first = new MBThread("One",orderedThread); second = new MBThread("Two",orderedThread); third = new MBThread("Three",orderedThread); second.start(); first.start(); third.start(); } public void display(String msg) { synchronized (msg) { for(int i = 1;i<=20;i++) { System.out.println("Name = " + msg); } } } } class MBThread extends Thread { String name; OrderedThread orderT; MBThread(String name, OrderedThread orderT) { this.name = name; this.orderT = orderT; } public void run () { orderT.display(name); } } The solution state that two,one and three will be printed in an indefinite order. Do you understand why is this the case? Also, I ran the code in eclipse and it was printing two,one three 20 times each in order. Lastly is there a way to print it in order? Thanks
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
This is a good exercise. Exploration and experimentation like this is great, so I'll try not to give you too much in the way of answers. When I ran this from the command line the names One Two and Three were nicely scrambled. The synchronized block assures that only one thread can get the monitor of some object at a time. Are all three of your threads trying to get the monitor of the same "name" object? If not, what effect does synchronize on three different objects have? Try changing the synchronized block to sync on (this). Then all three threads will sync on the same object for sure. See what that does to the scrambling. This illustrates a problem with a long-running synchronized block because the threads don't get much chance to interleave. If you could get this tuned perfectly so it prints One 20 times then Two 20 times then Three 20 times, what would be the benefit of using threads?
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
Promod kumar
Ranch Hand
Joined: Jun 26, 2006
Posts: 90
|
|
To see indefinite, scrambled results, I changed the for loop to As far as what is going on in the code, I am still trying to figure it out.
|
 |
Promod kumar
Ranch Hand
Joined: Jun 26, 2006
Posts: 90
|
|
Here is a couple of variations on how to have them print not scrambled(although you might want to think about Stan's question about the purpose of threads etc). In the first approach, I am sending in the same String "one" to all the constructors. Let me know if this helps or if you need further explanation.
|
 |
 |
|
|
subject: Threading and synchronization
|
|
|