可重入锁(Reentrant locks)。这些锁允许一个线程多次获得锁,只要它释放锁的次数相同。
半挂锁(Semaphores)。这些锁允许指定数量的线程同时获得该锁。
读写锁(Read-write locks)。这些锁允许多个线程获取锁进行读取,但每次只有一个线程可以获取锁进行写入。
戳记锁(Stamped locks:)。这些锁类似于读写锁,但它们允许多个线程同时获取锁进行读取,从而实现更有效的锁定。
0.内置的synchronized这里不多做赘述
pass
1.Reentrant locks
import java.util.concurrent.locks.ReentrantLock;
public class MyClass {
// Create a new reentrant lock
private static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
// Acquire the lock
lock.lock();
try {
// Access shared resource
} finally {
// Release the lock
lock.unlock();
}
}
}
2.Semaphore
import java.util.concurrent.Semaphore;
public class MyClass {
// Create a new semaphore with a given number of permits
private static final Semaphore semaphore = new Semaphore(5);
public static void main(String[] args) {
// Acquire a permit from the semaphore
semaphore.acquire();
try {
// Access shared resource
} finally {
// Release the permit
semaphore.release();
}
}
}
2.Read-write locks
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyClass {
// Create a new read-write lock
private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static void main(String[] args) {
// Acquire the lock for reading
lock.readLock().lock();
try {
// Access shared resource for reading
} finally {
// Release the lock
lock.readLock().unlock();
}
// Acquire the lock for writing
lock.writeLock().lock();
try {
// Access shared resource for writing
} finally {
// Release the lock
lock.writeLock().unlock();
}
}
}
4.戳记锁
import java.util.concurrent.locks.StampedLock;
public class MyClass {
// Create a new stamped lock
private static final StampedLock lock = new StampedLock();
public static void main(String[] args) {
// Acquire the lock for reading
long stamp = lock.readLock();
try {
// Access shared resource for reading
} finally {
// Release the lock
lock.unlockRead(stamp);
}
// Acquire the lock for writing
stamp = lock.writeLock();
try {
// Access shared resource for writing
} finally {
// Release the lock
lock.unlockWrite(stamp);
}
}
}