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


Please Help Members By Posting Answers For Below Questions

Does java set allow duplicates?

520


What are the data types supported by java?

542


When would you use a static class?

578


Is class is a data type?

568


what do you understand by synchronization? : Java thread

544






What is the function of java?

508


What are the rules for variable declaration?

496


Which sorting is used in arrays sort in java?

581


Can we inherit inner class?

519


What is string immutability?

533


What is the use of arraylist class in java?

547


Can we serialize singleton class?

523


Why do we need strings in java?

519


What is visibility mode?

525


How do you use parseint in java?

507