1、JUC
java.util.concurrent在并发编程中使用的工具类
2、Lock
Lock是java.util.concurrent.locks下的接口
3、Lock跟Synchronized区别
- synchronized是java内置关键词,在jvm层面;Lock是个java接口
- synchronized无法判断是否获取锁的状态,Lock可以判断是否获取到锁
- synchronized会自动释放锁(a线程执行完同步代码块会释放锁,b线程执行过程中发生异常会释放锁);Lock需要在finally中手工释放锁(unlock()方法释放锁),否则容易造成死锁
- 用synchronized关键字的两个线程1和线程2,如果当前线程1获得锁,线程2线程等待。如果线程1阻塞,线程2则会一直等待下去,而Lock锁就不一定会等待下去,如果尝试获取不到锁,线程可以不用一直等待就结束了;
- synchronized的锁可重入、不可中断、非公平,而Lock锁可重入、可判断、可公平(两者皆可)
- Lock锁适合大量同步的代码的同步问题,synchronized锁适合代码少量的同步问题
4、Lock使用
class X {
//Lock是接口,ReentrantLock()是其中一个实现
//private Lock lock = new ReentrantLock();
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
5、售卖电影票例子
/**
* 资源类
*/
class Ticket{
private int count = 20;
private Lock lock = new ReentrantLock();
public void sale(){
//上锁
lock.lock();
try {
if (count > 0){
count--;
System.out.println(Thread.currentThread().getName()+"正在买票,还是剩下" + count);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//手动释放锁
lock.unlock();
}
}
}
public class LockTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(()->{
for (int i = 0; i < 20; i++) {
ticket.sale();
}
},"AA").start();
new Thread(()->{
for (int i = 0; i < 20; i++) {
ticket.sale();
}
},"BB").start();
new Thread(()->{
for (int i = 0; i < 20; i++) {
ticket.sale();
}
},"CC").start();
}
}