You might think that this question is duplicate of this one but no answers of that question helps me for understanding synchronized
method in android. I searched a lot on google for understanding synchronized
methods and i found some answer but they didn't help me to perfectly understand Synchronized
methods because no answer has any perfect practical example.
I have tried to understand synchronized
method by implement 2 synchronized
methods in my code and executing them concurrently but i am failed in properly implementing them. So, please provide explanation of synchronized
method with simple example so, others like me also can understand it simply and in a faster way.
UPDATE
I am not sure i am going in right direction or not but i have tried following code which have 2 synchronized methods.
synchronized void add() {
counter++;
Log.e("JK", String.valueOf(counter));
}
synchronized void minus() {
counter--;
Log.e("JK", String.valueOf(counter));
}
and i have called this methods in two different threads using below code.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
synchronized (counter++) {
add();
}
}
},500);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
minus();
}
},1000);