java中的锁
1. 重量级锁 synchronized , 是重入锁
可以修饰方法,或者锁对象
// 锁方法
synchronized void aaa() {
count++;
}
// 锁对象
void aaa() {
synchronized (Abc.class) {
count++;
}
}
2. ReentrantLock 是重入锁
import java.util.concurrent.locks.ReentrantLock;
public class Abc {
int count = 0;
private final ReentrantLock lock = new ReentrantLock();
void aaa() {
try {
lock.lock();
// 超时还没获得锁就抛异常
// lock.tryLock(1, TimeUnit.MICROSECONDS);
// lock.lockInterruptibly(); // 获取锁,并一直等待,但等待过程中线程可以被中断
count++;
} finally {
lock.unlock();
}
}
void ccc() {
try {
lock.lock();
count++;
// 测试 ReentrantLock 是否为重入锁,可以执行,所以是重入锁
try {
lock.lock();
count++;
} finally {
lock.unlock();
}
} finally {
lock.unlock();
}
}
}
3. ReentrantReadWriteLock 读写锁
public class Abc {
int count = 0;
private final ReentrantLock lock = new ReentrantLock();
// 读写锁
final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
void aaa() {
try {
writeLock.lock();
// 超时还没获得锁就抛异常
// writeLock.tryLock(1, TimeUnit.MICROSECONDS);
// writeLock.lockInterruptibly(); // 获取锁,并一直等待,但等待过程中线程可以被中断
count++;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
}
简单的代码demo
查看代码
import java.util.concurrent.locks.ReentrantLock;
public class Abc {
int count = 0;
private final ReentrantLock lock = new ReentrantLock();
void aaa() {
try {
lock.lock();
count++;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final Abc a = new Abc();
// 建4条线程,调用aaa() 方法
for (int i = 0; i < 4; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 10000; j++) {
a.aaa();
}
});
thread.start();
}
Thread.sleep(3000); // 睡一段时间,上面的线程都执行完
System.out.println("a.count = " + a.count);
}
}

浙公网安备 33010602011771号