Only true if the monitor lock is not implied. i.e., synchronized methods imply that object "this" is accessible by no-other-objects whilst that thread has the lock. Whilst no threads are accessing the locked portions then readC is concurrent. When they are, readC is blocked.
... snip ... No, synchronized methods block the entire instance.
Run the following code:
public class Test { public synchronized void criticalA() { System.out.println("Test.criticalA: I'm sleeping."); try { Thread.sleep(5000); } catch (Throwable t) { } System.out.println("Test.criticalA: I'm done."); }
public synchronized void criticalB() { System.out.println("Test.criticalB: I'm sleeping."); try { Thread.sleep(5000); } catch (Throwable t) { } System.out.println("Test.criticalB: I'm done."); }
public void readC() { System.out.println("Test.readC: I'm getting called!"); }
public static void main(String[] args) { final Test test = new Test();
Thread t1 = new Thread(new Runnable() { public void run() { test.criticalA(); } }); t1.start();
Thread t2 = new Thread(new Runnable() { public void run() { test.criticalB(); } }); t2.start();
Thread t3 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 10; i++) { test.readC(); } } }); t3.start(); } }
and it will output:
Test.criticalA: I'm sleeping. Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.readC: I'm getting called! Test.criticalA: I'm done. Test.criticalB: I'm sleeping. Test.criticalB: I'm done.
Only synchronized blocks and methods that share the same monitor will block each other. An unsynchronized method has no monitor on it and therefore can be called any time regardless of the state of the instance monitor.
ms |