在jdk1.5后新增的ReentrantLock类同样可达到此效果,且在使用上比synchronized更加灵活
相关API:
使用ReentrantLock实现同步
lock()方法:上锁
unlock()方法:释放锁
使用Condition实现等待/通知 类似于 wait()和notify()及notifyAll()
Lock锁底层基于AQS实现,需要自己封装实现自旋锁。
Synchronized —属于JDK 关键字 底层属于 C++虚拟机底层实现
Lock锁底层基于AQS实现-- 变为重量级
Synchronized 底层原理—锁的升级过程
Lock 过程中 注意 获取锁 释放锁
ReentrantLock用法
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
-
@author zhuimeng
*/
public class Thread09 implements Runnable {
private int count = 100;
private Lock lock = new ReentrantLock();@Override
public void run() {
while (true) {
try {
Thread.sleep(30);
} catch (Exception e) {} try { // 获取锁 lock.lock(); if (count > 1) { count--; System.out.println(Thread.currentThread().getName() + "," + count); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放锁 lock.unlock(); } }
}
public static void main(String[] args) {
Thread09 thread09 = new Thread09();
Thread t1 = new Thread(thread09);
Thread t2 = new Thread(thread09);
t1.start();
t2.start();
}
}
Condition用法
public class Thread10 {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public static void main(String[] args) {
Thread10 thread10 = new Thread10();
try {
thread10.print();
Thread.sleep(3000);
thread10.signal();
} catch (Exception e) {
}
}
public void print() {
new Thread(() -> {
try {
// 释放锁 同时当前线程阻塞
lock.lock();
System.out.println(Thread.currentThread().getName() + ",1");
condition.await();
System.out.println(Thread.currentThread().getName() + ",2");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
}
public void signal() {
try {
lock.lock();
condition.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}