• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Code has me confused

 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21003
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sanjit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic