| Author |
Thread Code has me confused
|
victor kamat
Ranch Hand
Joined: Jan 10, 2007
Posts: 247
|
|
public class MyRun implements Runnable { Object Lock = new Object(); int K = 100; public static void main(String... args) { MyRun rt = new MyRun(); Thread t1 = new Thread( rt,"A"); Thread t2 = new Thread(rt); t1.start(); try { Thread.sleep(50); } catch (Exception e) {} t2.start(); } public void run() { int k = 100; synchronized (Lock ) { if ( Thread.currentThread().getName().equals("A") ) K = k = 200; System.out.println(k + " " + K); } } } The output is 200 200 100 200 This has me completely confused. The code is locking on the same object so why is the value of k in the second line NOT 200 as it is for K ???
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
This has me completely confused. The code is locking on the same object so why is the value of k in the second line NOT 200 as it is for K ???
The lower-case "k" variable, is a local variable. Every call to the method gets its own copy. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Sanjit Kumar
Ranch Hand
Joined: Dec 04, 2006
Posts: 35
|
|
Hi Victor, It seems you still have some problem in understanding of concurrency issues. Every Threads share instance variables not local variables.So for thread t2 if condition does not get true, so small k remains 100 and since capital K is shared so its value got changed by thread t1. That's why you are getting 100 200 for thread t2.
|
 |
Sanjit Kumar
Ranch Hand
Joined: Dec 04, 2006
Posts: 35
|
|
Hi Victor, It seems you still have some problem in understanding of concurrency issues. Every Threads share instance variables not local variables.So for thread t2 if condition does not get true, so small k remains 100 and since capital K is shared so its value got changed by thread t1. That's why you are getting 100 200 for thread t2. ------------------------------------------------------------------------------ No one is intelligent by birth
|
 |
 |
|
|
subject: Thread Code has me confused
|
|
|