Given the following code, which statements are true about the objects referenced by the fields i, j, and k, given that any thread may call the methods a()
, b()
, and c()
at any time?.
class Counter {/* ww w . ja v a 2s.c o m*/ int v = 0; synchronized void inc() { v++; } synchronized void dec() { v--; } } public class Main { 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 void c() { k.inc(); System.out.println("c"); k.dec(); } }
Select the two correct answers.
(a) and (b)
If a thread is executing method b()
on an object, it is guaranteed that no other thread executes methods a()
and b()
concurrently.
Therefore, the invocation counters i and j will never show more than one concurrent invocation.
Two threads can concurrently be executing methods b()
and c()
.
Therefore, the invocation counter k can easily show more than one concurrent invocation.