This is related to threads. I have a class with synchronized
method m1(). Can I create different instances of this class
and execute the m1() for different threads?
Answer Posted / qim2010
Putting code inside a synchronized block makes the compiler
append instructions to acquire the lock on the specified
object before executing the code, and release it afterwards
(either because the code finishes normally or abnormally).
Between acquiring the lock and releasing it, a thread is
said to "own" the lock. At the point of Thread A wanting to
acquire the lock, if Thread B already owns the it, then
Thread A must wait for Thread B to release it. Thus in the
example below, simultaneous calls to increment() and
getCount() will always behave as expected; a read could not
"step in" while another thread was in the middle of
incrementing.
public class Counter {
private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
public int getCount() {
synchronized (this) {
return count;
}
}
}
Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
Can we extend private class in java?
Can we split string with in java?
How is string immutable in java?
Why destructor is not used in java?
What are the restriction imposed on a static method or a static block of code?
What is a instance variable?
Are the imports checked for validity at compile time? Will the code containing an import such as java.lang.abcd compile?
What is the symbol for average?
How do listeners work?
What is the major difference between linkedlist and arraylist?
Do I need java on my computer?
How to perform selection sort in java?
Why do we need autoboxing in java?
How to call one constructor from the other constructor ?
Is string pool garbage collected?