How to use Java multi-threading locks
In Java, you can implement thread locking mechanisms using either the synchronized keyword or the ReentrantLock class.
- Use the synchronized keyword:
public class MyObject {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized void decrement() {
count--;
}
}
In the above example, the synchronized keyword is used to decorate the increment() and decrement() methods, so that when calling these two methods, the MyObject object is locked, ensuring that only one thread can access these two methods at the same time.
- Utilizing the ReentrantLock class:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyObject {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public void decrement() {
lock.lock();
try {
count--;
} finally {
lock.unlock();
}
}
}
In the example above, a lock object named ‘lock’ is created using the ReentrantLock class. The lock() method is used to lock the object in the increment() and decrement() methods, while the unlock() method is used to release the lock. This allows for more flexible control over lock acquisition and release.