这里我们讲解使用Lock来给线程加锁 就像我们之前使用synchronized方法来加锁一样
Lock是一个接口 我们要使用多态的方式 使用接口的实现类对象ReentrentLock 来创建对向
ReentrentLock 构造方法
ReentrentLock();
成员方法
lock() ; 添加锁
unLock() ; 释放锁
线程代码
public class SaleTackets implements Runnable{
private int tickets = 1 ;
//创建一个锁的对象
private Lock lock = new ReentrantLock(); //使用多态创建对象
@Override
public void run() {
while (true){
try{
//添加锁
lock.lock();
if (tickets <= 100){
System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票");
tickets++;
}
//休息一下
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}finally {
//释放锁 为了防止释放锁之前程序就因为异常退出了,而导致锁没有被打开
// 我们要使用try{} finally{} 让锁一定会被打开
lock.unlock();
}
}
}
}
测试代码 mian方法
public class testDemo {
public static void main(String[] args) {
//线程资源
SaleTackets saleTackets = new SaleTackets();
//创建线程
//创建线程
Thread thread1 = new Thread(saleTackets,"窗口一");
Thread thread2 = new Thread(saleTackets,"窗口二");
Thread thread3 = new Thread(saleTackets,"窗口三");
//开启线程
thread1.start();
thread2.start();
thread3.start();
}
}