wood burning stoves 2.0*
The moose likes Java in General and the fly likes static synchronized method 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 » Java » Java in General
Reply locked New topic
Author

static synchronized method

tanu dua
Ranch Hand

Joined: Apr 05, 2004
Posts: 145
class static_synchronized
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
}
}

class Producer implements Runnable
{
Q q;

Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}

public void run()
{
q.put();
}
}


class Consumer implements Runnable
{
Q q;

Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}

public void run()
{
q.get();

}
}


class Q
{
synchronized void get()
{
int i=0;
while(i<=5)
{
if(i==2) try{Thread.sleep(1000);}catch(Exception e){}
System.out.println("get");
i++;
}
}

synchronized void put()
{
int i=0;
while(i<=5)
{
if(i==2) try{Thread.sleep(1000);}catch(Exception e){}
System.out.println("put");
i++;
}
}
}


class static_synchronized
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
}
}


Output: 6 put followed by 6 get

class Producer implements Runnable
{
Q q;

Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}

public void run()
{
q.put();
}
}


class Consumer implements Runnable
{
Q q;

Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}

public void run()
{
q.get();

}
}


class Q
{
synchronized void get()
{
int i=0;
while(i<=5)
{
if(i==2) try{Thread.sleep(1000);}catch(Exception e){}
System.out.println("get");
i++;
}
}

static synchronized void put()
{
int i=0;
while(i<=5)
{
if(i==2) try{Thread.sleep(1000);}catch(Exception e){}
System.out.println("put");
i++;
}
}
}

Output: 2 put 2 get 4 put 4 get.

The only differnce in the above 2 progs is that first version has non-static synchronized put method
however second version has static synchronized method.

Problem: Why the output differs?

Thanx
Waiting someone to reply.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Please don't cross post. Continue discussion at http://www.coderanch.com/t/232626/threads/java/static-synchronized-method


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
 
subject: static synchronized method
 
Similar Threads
static synchronized method
Thread's
Thread's
threads synchronization problem
Concurrency Utilities