File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Code has me confused Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Code has me confused" Watch "Thread Code has me confused" New topic
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: 18916
    
  40

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread Code has me confused