Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Watch "Thread 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.
Pratap Reddy
Ranch Hand

Joined: Jan 05, 2001
Posts: 36
Hi Nitin,
Let me try to explain , Thread 1 once complete the
synchronized method then automatically releases the lock.
Your thinking will be right if you use some wait() and
notifyAll() methods. While Thread 1 put's numbers Thread
2 need to wait(). Once Thread 1 completes all put's
method then notifyAll(), then Thread 2 will start
executing.
Pratap
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread's
 
Similar Threads
Thread's
Thread's
Thread's
thread's
static synchronized method