JDK5以后提供了一个新的锁对象Lock,Lock是一个接口,ReentrantLock是Lock的实现类
- package com.kxg_11;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- /*
- * Lock:
- * lock():添加锁
- * unlock():释放锁
- */
- public class SellTicekt implements Runnable {
- private int ticket = 100;
- // 创建Lock接口的实现类ReentrantLock
- private Lock lock = new ReentrantLock();
- @Override
- public void run() {
- while (true) {
- try {
- lock.lock();
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (ticket > 0) {
- System.out.println(Thread.currentThread().getName()
- + "正在出售第" + (ticket--) + "张票");
- }
- } finally {
- lock.unlock();
- }
- }
- }
- }
复制代码
|
|