Hello all... Khalid Mughal - Threads Page 282 public class VolThread extends Thread { static Object lock1 = new Object(); static Object lock2 = new Object(); static volatile int i1,i2,j1,j2,k1,k2; public void run() { while (true) { doit(); check(); } } void doit() { synchronized (lock1) { i1++; } j1++; synchronized (lock2) { k1++; k2++; } j2++; synchronized (lock1) { i2++; } } void check() { if (i1!=i2) System.out.println("i"); if (j1!=j2) System.out.println("j"); if (k1!=k2) System.out.println("k"); } public static void main(String[] args) { System.out.println("Hello "); new VolThread().start(); new VolThread().start(); } } For the above Program, I have 2 Questions :- Q.1) Does removing the Word Volatile in above have any effect on the Outcome ? Q. 2) Suppose if Thread 1 is Executing Synchronized(lock1), then Thread 2 can Execute the statement j1++. OR Thread 2 has to wait for Thread1 to Release the lock ? Thanks.
Shah Chunky - Sun Certified Java2 Programmer.
vivek nashine
Greenhorn
Joined: May 17, 2001
Posts: 4
posted
0
Hello friend, The answers for U'r queries: 1)Yes,not declaring the variables in this code can have a changeable effect on the outcome,b'coz in this code there is a possibility of two thread accessing the same variable. 2)no, any other step after synchronized will be executed only after the current syncronized block's execution is completed by the thread.
Scott Appleton
Ranch Hand
Joined: May 07, 2001
Posts: 195
posted
0
My understanding is that Thread2 *can* execute the j1++ line while Thread1 holds the monitor on lock1 because the j1++ line of code is not within the synchronized block of code where the monitor is applicable.
Mikael Jonasson
Ranch Hand
Joined: May 16, 2001
Posts: 158
posted
0
Remeber that there is no end to the while-loop, and there is no telling when a given thread will loose focus. Thread 2 might be right after the syncronzie block when it stops, then thread 1 just enters it when it stops. This will give a situation where thread 1 is in the sync-block, while thread 2 executes j1++; /Mike
jeena jose
Ranch Hand
Joined: May 06, 2001
Posts: 69
posted
0
can someone explain to me the importance of volatile keyword in detail???
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.