Lock(接口)
在JDK5以后Java提供了一个更具体的锁对象——Lock:
Lock为接口,ReentrantLock为子实现类
1.成员方法:
(1)public void lock()获取锁
(2)public void unlock()试图释放此锁
格式:
try{
Lock对象.lock(); //获取锁
//···
}finally{
Lock对象. unlock(); // 释放锁
}
例:模拟电影院售票,一共100张票,三个窗口同时开售
// 测试类
public class SellTicketTest {
public static void main(String[] args) {
// 创建SellTicket对象
SellTicket st = new SellTicket();
// 创建线程
Thread t1 = new Thread(st, "窗口1");
Thread t2 = new Thread(st, "窗口2");
Thread t3 = new Thread(st, "窗口3");
// 启动线程
t1.start();
t2.start();
t3.start();
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
// 自定义定义线程类
public class SellTicket implements Runnable {
// 定义共有数据100张票
private static int tickets = 100;
// 定义Lock锁对象
Lock lock = new ReentrantLock();
@Override
public void run() {
// 假设一直有票
while (true) {
try {
// 获取锁
lock.lock();
if (tickets > 0) {
// 线程睡眠0.1秒
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票");
}
} finally {
// 释放锁
lock.unlock();
}
}
}
}