Java MCQ: Which of the following mechanisms is used to achieve thread synchronization in Java?
Answer:
Explanation:
The synchronized
block in Java is used to achieve thread synchronization. Synchronization is the mechanism that ensures that only one thread can access a resource (such as a method or an object) at a time. This is crucial in multithreaded programming to prevent race conditions, where multiple threads try to modify the same data concurrently, leading to inconsistent results.
Here’s an example of using a synchronized
block:
public class Counter {
private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
public int getCount() {
return count;
}
}
In this example, the increment()
method uses a synchronized
block to ensure that only one thread can increment the count
variable at a time. The synchronized (this)
statement locks the current object, preventing other threads from entering the block until the current thread has finished executing it.
The synchronized
block is one of the primary tools for thread synchronization in Java, helping to maintain data consistency and avoid concurrency issues in multithreaded applications.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html