Originally posted by kevin goon:
Hi, I posted this question before but It wasn��t clear what the correct answers are. i'd appreciate it if someone can quickly shed light on this. Thank you.
public class SyncTest
2. private int x;
3. private int y;
4. private synchronized void set X (int i) x=i;
5. private synchronized void set Y (int i) y=i;
6. public void setXY (int i) set X(i); set Y(i);
7. public synchronized boolean check() return X != Y;
8.
Under which conditions will check() return when called from a different class
A. check() can never return true
B. check() can return true when set XY is called by multiple threads
C. check() can true when multiple threads call set X and set Y separately
D. check() can only return true if synchTest is changed to allow x and y to be set
Separately
ans): a,d ???
Q2)
Conside below
public static void main(String args[] ){
X that = new X();
X hey = new X();
(new Thread(that)).start();
(new Thread(hey)).start();
}
public synchronized void run(){
for( ; ; ){
x++;
y++;
System.out.println("x=" + x + ", y=" +y);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}//end of for loop
}//end of run()
}//end of class
Output?
I thought by using synchronized run(), only one Object thread is run and that the other Object thread("hey) must wait till the first one("that") is finished. thus producing
1 1
2 2.. and so on..
but when i ran it, it output
1 1
1 1
2 2
2 2 ... Why? I think I'm getting very confused with the thread and how the idea of synchronization works..
Can Someone give a really Easy and Clear explanation of synchronization??? on methods and blocks??
Thank you so much!! =))
Originally posted by kevin goon:
A. check() can never return true
B. check() can return true when set XY is called by multiple threads
C. check() can true when multiple threads call set X and set Y separately
D. check() can only return true if synchTest is changed to allow x and y to be set
Separately
ans): a,d ???
Thank you so much!! =))
Originally posted by Scott Appleton:
Kevin, I'll stand by my response to your original post unless someone convinces me otherwise (http://www.javaranch.com/ubb/Forum24/HTML/010384.html)
I concur with William's answer to your second question -- you've created 2 separate objects for the 2 threads to act upon, so they are acting completely independently of each other and the synchonization of the run() method is irrelevant in this example. If you point both threads to either hey or that, then you would get the output you were expecting.
Consider Paul's rocket mass heater. |