public void add(int value){
synchronized(this){
this.count += value;
}
}
Notice how the Java synchronized block construct takes an object in parentheses. In the example "this" is used, which is the instance the add method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object.
below using class level lock
public void add(int value){
synchronized(Data.class){
this.count += value;
}
}
In below code thread run one by one, once a thread complete his work then another will start due to lock on same string value "abc", then the compiler might actually use the same String object behind the scenes.
void method1(String threadName){
synchronized ("abc") {
System.out.println(threadName + ":method 1 running");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + ":sleep over");
method2(threadName);
}
}
void method2(String threadName){
synchronized ("abc"){
System.out.println(threadName+":method 2 running");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName+":sleep over");
}}
No comments:
Post a Comment