1.ReentrantLock
在Java多线程中,可以使用synchronized关键字来实现线程之间的同步互斥。但是在Java 1.5中新增了ReentrantLock类也能达到同样的效果。并且扩展了许多功能。比synchronized更加灵活。
代码演示
新建业务类
public class Business {
private Lock lock = new ReentrantLock();
public void print() {
//lock.lock();
for (int i = 0; i < 5; i++) {
System.out.println(String.format("%s:%d", Thread.currentThread().getName(), i));
}
//lock.unlock();
}
}
- 新建线程A
public class ThreadA extends Thread {
private Business business;
public ThreadA(Business business) {
super();
this.business = business;
}
@Override
public void run() {
business.print();
}
}
- 新建线程B
public class ThreadB extends Thread {
private Business business;
public ThreadB(Business business){
this.business=business;
}
@Override
public void run() {
business.print();
}
}
- Client
public class Client {
public static void main(String[] args) {
Business business = new Business();
ThreadA a = new ThreadA(business);
ThreadB b = new ThreadB(business);
a.start();
b.start();
}
}
- 没加锁的结果
线程B:0
线程B:1
线程B:2
线程B:3
线程B:4
线程A:0
线程A:1
线程A:2
线程A:3
线程A:4
- 加锁后的结果
线程B:0
线程B:1
线程B:2
线程B:3
线程B:4
线程A:0
线程A:1
线程A:2
线程A:3
线程A:4
由此可看出,ReentrantLock实现了synchronized的同步的功能。lock.lock()是获取锁。lock.unlock()是释放锁。
1.1结合Condition实现wait与notify功能
关键字synchronized与wait及notify结合,可以实现等待、通知模式。而ReentrantLock与Condition结合也可以实现同样的功能。
代码演示
新建业务类
public class Business {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private int num;
public void print() {
try {
lock.lock();
for (int i = 0; i < 5; i++) {
System.out.println(String.format("%s:%d", Thread.currentThread().getName(), i));
num = i;
if (i == 2){
condition.await();
System.out.println("接受到信号,执行完毕");
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
lock.unlock();
}
}
public void notifyPrint() {
lock.lock();
if (num == 2)
condition.signal();
lock.unlock();
}
}
- 新建线程A
public class ThreadA extends Thread {
private Business business;
public ThreadA(Business business) {
super();
this.business = business;
}
@Override
public void run() {
business.print();
}
}
- 新建线程B
public class ThreadB extends Thread {
private Business business;
public ThreadB(Business business) {
this.business = business;
}
@Override
public void run() {
business.notifyPrint();
}
}
- Client
public class Client {
public static void main(String[] args) throws InterruptedException {
Business business = new Business();
ThreadA a = new ThreadA(business);
a.setName("线程A");
ThreadB b = new ThreadB(business);
b.setName("线程B");
a.start();
Thread.sleep(2000);
b.start();
}
}
- 结果
Connected to the target VM, address: '127.0.0.1:62623', transport: 'socket'
线程A:0
线程A:1
线程A:2
Disconnected from the target VM, address: '127.0.0.1:62623', transport: 'socket'
接受到信号,执行完毕
线程A:3
线程A:4
下面图标表示Object里面的类的方法与Condition类的方法对比
Object | Condition |
---|---|
wait() | await() |
wait(long timeout) | await(long time, TimeUnit unit) |
notify() | signal() |
notifyAll() | signalAll() |
1.2 Condition的部分唤醒
在服务类中创建多个Condition实例。进行对其分组操作。
private Condition condition = lock.newCondition();
private Condition condition2 = lock.newCondition();
1.3公平锁与非公平锁
公平锁:线程获取锁的顺序是按照线程加锁的顺序来分配的。即先进先出的顺序(FIFO)。
非公平锁:获取锁的抢占机制,是随机获得锁的。
- ReentrantLock的构造函数
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
传入true为公平锁,传入false为非公平锁。
1.4ReentrantLock及Condition其他重要方法
- 1.getHoldCount
查询当前线程保持锁定的个数,也就是调用lock()的次数
public int getHoldCount() {
return sync.getHoldCount();
}
- 2.getQueueLength
计算正等待获取此锁定的线程数。比如一个线程在锁内休眠,其他9个线程正在等待,那么调用此方法返回9。
public final int getQueueLength() {
return sync.getQueueLength();
}
- 3.getWaitQueueLength
返回给定条件的Condition相关的等待此锁的线程数。
public int getWaitQueueLength(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
}
- 4.hasQueuedThread
查询指定的线程是否正在等待获取此锁
public final boolean hasQueuedThread(Thread thread) {
return sync.isQueued(thread);
}
- 5.hasQueuedThreads
查询是否有线程正在等待获取此锁
public final boolean hasQueuedThreads() {
return sync.hasQueuedThreads();
}
- 6.hasWaiters
根据Condition条件去查询是否有线程正在等待获取此锁
public boolean hasWaiters(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
}
- 7.isFair
判断是不是公平锁
public final boolean isFair() {
return sync instanceof FairSync;
}
- 8.isHeldByCurrentThread
查询当前是否保持锁定
public boolean isHeldByCurrentThread() {
return sync.isHeldExclusively();
}
- 9.isLocked
判断当前锁是否由任意线程锁定
public boolean isLocked() {
return sync.isLocked();
}
- 10.lockInterruptibly
如果当前线程未被中断,则获取获取锁定,(相当于lock())如果已经中断则抛出异常
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
- 11.tryLock
当锁没有被其他线程占用,则获取锁定。
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
- 12.tryLock(long timeout, TimeUnit unit)
在给定的时间内,锁没有被其他线程占用,则获取锁
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
- 13.awaitUninterruptibly
线程在等待的时候,线程若主动抛出异常,则相对应的程序也不会抛出异常。
public final void awaitUninterruptibly() {
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean interrupted = false;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if (Thread.interrupted())
interrupted = true;
}
if (acquireQueued(node, savedState) || interrupted)
selfInterrupt();
}
- 14.awaitUntil
某线程在指定的时间内处于等待状态,超过时间,自动运行线程。
public final boolean awaitUntil(Date deadline)
throws InterruptedException {
long abstime = deadline.getTime();
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (System.currentTimeMillis() > abstime) {
timedout = transferAfterCancelledWait(node);
break;
}
LockSupport.parkUntil(this, abstime);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return !timedout;
}
2.ReentrantReadWriteLock
ReentrantLock具有完全互斥排他的效果,即同一时间只有一个线程在执行ReentrantLock.Lock()方法后面的任务。
这样虽然保证了实例变量的线程安全性,但是效率却是低下的。这时候就诞生了读写锁ReentrantReadWriteLock。
读写锁有两个锁:
- 1.共享锁:读操作相关的锁
- 2.排他锁:写操作相关的锁
private ReentrantReadWriteLock lock1 = new ReentrantReadWriteLock();
lock1.writeLock().lock();
lock1.writeLock().unlock();
lock1.readLock().lock();
lock1.readLock().unlock();
同一个类中,有两个及两个以上的方法。一个使用读锁,一个使用写锁。那么它们是互斥的。只有所有的方法是读锁,才是不相互干扰,不排斥的。