public class MyClass { public synchronized void log1(String msg1, String msg2){ log.writeln(msg1); log.writeln(msg2); } public void log2(String msg1, String msg2){ synchronized(this){ log.writeln(msg1); log.writeln(msg2); } } }
Only one thread can execute inside a Java code block synchronized on the same monitor object.
The following two examples are both synchronized on the instance they are called on. They are therefore equivalent with respect to synchronization:
Thus only a single thread can execute inside either of the two synchronized blocks in this example.
public class Counter{ private static int count = 0; public synchronized int getCount(){ return count; } public synchronized setCount(int count){ this.count = count; } }// only either will be run by any thread
No comments:
Post a Comment