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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic
Author

Thread's

nitin sharma
Ranch Hand

Joined: Feb 24, 2001
Posts: 290
class Q
{
int n;
synchronized int get()
{
System.out.println("got:"+n);
return n;
}
synchronized void put(int n)
{
this.n=n;
System.out.println("put:"+n);
}
}
class producer implements Runnable
{
Q q;
producer(Q q)
{
this.q=q;
new Thread(this,"producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class consumer implements Runnable
{
Q q;
consumer(Q q)
{
this.q=q;
new Thread(this,"consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class pc
{
public static void main(String[]args)
{
Q q=new Q();
new producer(q);
new consumer(q);
System.out.println("press control c to stop ");
}
}
hello,
In the above given programme i have a Q class inside which i have two synchronized method's got() and put().I have created two thread's inside the pc class and invoking those synchronized method's.
Now my question is when one thread is inside the synchronized method then no other thread can access any synchronized of the class on the same instance.But in the above programme both the thread's are able to execute the synchronized method's at the same time.Please throw some light on it,correct me if i am wrong.

QUESTION FROM COMPLETE REFERENCE PAGE NO 298.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Thread's