aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronization" Watch "synchronization" New topic
Author

synchronization

rohitt kumarr
Greenhorn

Joined: Jul 27, 2006
Posts: 5
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Jul 27, 2006
Posts: 5
Yes,You are right.Got it.Thanks a lot!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronization