Bookmark Topic Watch Topic
  • New Topic

static synchronized method

 
tanu dua
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please don't cross post. Continue discussion at http://www.coderanch.com/t/232626/threads/java/static-synchronized-method
 
    Bookmark Topic Watch Topic
  • New Topic