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
Explain how to convert any java object into byte array.
How do you find the absolute value?
What are the different types of data structures in java?
Can we create more than one object singleton class?
Is java se free?
Differences between traditional programming language and object oriented programming language?
Difference between Linked list and Queue?
Explain the different forms of polymorphism?
What does nullpointerexception mean?
Why java is call by value?
What does main method?
Justify your answer that you can't define a method inside another method in java, if you can then how?
How we create object in copy constructor?
What is difference between hashset and hashmap in java?
What is the use of arraylist in java?