1,创建锁
2,加锁
3,解锁
package com.liu.demo01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SaleTickeDemo01 {
public static void main(String[] args) {
Ticket ticket = new Ticket();
//并发线程操作同一个资源类
new Thread(()->{for (int i = 0; i < 50; i++)ticket.sale();},"A").start();
new Thread(()->{ for (int i = 0; i < 50; i++)ticket.sale(); },"B").start();
new Thread(()->{ for (int i = 0; i < 50; i++)ticket.sale(); },"C").start();
}
}
//lock锁
class Ticket{
private int number = 50;
Lock lock = new ReentrantLock();//创建锁
public void sale(){
lock.lock();//加锁
try {
if(number>0){
System.out.println(Thread.currentThread().getName() + "卖出第" + (number--) + "张票,剩余" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//解锁
}
}
}