• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Threads & Synchronization

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which is true is a(), b() & c() can be called at any time
1> i.v is guaranteed always to be 0 or 1
2> j.v is guaranteed always to be 0 or 1
3> k.v is guaranteed always to be 0 or 1
4> j.v will always be >= k.v at any given time
5> k.v will always be >= j.v at any given time
I felt a,b,& c are all true as all methods are synchronized
and hence when the thread is in a() only i is inc & dec
so j & k remain unchanged
similarly b() & c().
But the answer given is only a & b.
Can someone please explain how this works?

class Counter{
int v = 0;
synchronized void inc() {v++;}
synchronized void dec() {v--;}
}
public class test extends Thread{
Counter i;
Counter j;
Counter k;
public synchronized void a(){
i.inc();
System.out.println("a");
i.dec();
}

public synchronized void b(){
i.inc(); j.inc(); k.inc();
System.out.println("b");
i.dec(); j.dec(); k.dec();
}
public synchronized void c(){
k.inc();
System.out.println("c");
k.dec();
}
}
Thanks
V Iyer
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic