Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization

 
rohitt kumarr
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All.Thanks for the replies on my previous doubt.Here is one doubt I have on synchronization.Please see the code.


class Tdemo implements Runnable
{
One o=new One();
public static void main(String args[])
{
Tdemo thread1=new Tdemo();
Tdemo thread2=new Tdemo();
Thread t1=new Thread(thread1);
Thread t2=new Thread(thread2);
t1.start();
t2.start();
}
public void run()
{
o.display();
}
}

class One
{
public synchronized void display()
{
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}


The method display() in the class One is synchronised.So,no two threads can access it with the same instance.But when I run the code,I get the out put

Thread 0
Thread 1
Thread 0
Thread 1....so on 10 times...

Please explain how the synchronized code is accessed by two threads at the same time?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe the problem here is that the method display is an instance method of One, and the variable o is an instance method of Tdemo.

You are creating two different Tdemo objects, and each Tdemo object has its own copy of an instance of One.

If you make the display method static, there will only be one display method, and you should see the behavior you expect.
 
rohitt kumarr
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes,You are right.Got it.Thanks a lot!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic