locks.Lock接口: 比同步方法/同步代码块使用更灵活
lock(): 获取锁。
unlock(): 释放锁。 释放资源的动作必须要执行
ReentrantLock类 是一个锁对象,在使用的时候,务必要保证锁对象的唯一性
Lock接口替换了同步代码块和同步方法
使用格式:
上锁: lock.lock();
try {
操作共享数据的代码;
} catch(...){
...
} finally {
lock.unlock();
}
Lock接口替换同步
@SuppressWarnings("All")
public class MyTicketsTask01 implements Runnable {
private int num = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while(true) {
try {
lock.lock();
if (num > 0) {
Thread.sleep(10);
String threadName = Thread.currentThread().getName();
System.out.println(threadName+"正在卖出第....."+num+".....张票");
num--;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public class Demo01Tickets {
public static void main(String[] args) {
MyTicketsTask02 task = new MyTicketsTask02();
Thread t1 = new Thread(task, "窗口");
Thread t2 = new Thread(task, "手机APP");
Thread t3 = new Thread(task, "网站");
t1.start();
t2.start();
t3.start();
}
}