In Java, the synchronized
keyword is used to acquire a lock on an object and ensure that only one thread can execute a block of code at a time. This can be useful for preventing race conditions and ensuring that shared resources are accessed in a thread-safe manner.
Here's an example of how to use the synchronized
keyword to synchronize access to a method:
public class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } }
In this example, the increment
and getCount
methods are synchronized, which means that only one thread can execute them at a time. If multiple threads try to access these methods concurrently, only one of them will be able to execute the method, and the others will have to wait until the lock on the object is released.
You can also use the synchronized
keyword to synchronize access to a block of code:
public class Counter { private int count = 0; public void increment() { synchronized (this) { count++; } } public int getCount() { synchronized (this) { return count; } } }
In this example, the increment
and getCount
methods synchronize access to the count
variable by acquiring a lock on the Counter
object.
You can find more information about the synchronized
keyword and how to use it in Java in the Java documentation.