package com.yanxizhu;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @description: ReentrantLock
* @author: <a href="mailto:batis@foxmail.com">清风</a>
* @date: 2022/3/19 12:37
* @version: 1.0
*/
public class LockDemo {
public static void main(String[] args) {
titck titck = new titck();
new Thread(titck,"线程1").start();
new Thread(titck,"线程2").start();
new Thread(titck,"线程3").start();
}
public static class titck implements Runnable{
Lock lock = new ReentrantLock();
private int titck = 100;
@Override
public void run() {
while(true){
lock.lock();
try{
if(titck>0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("剩余票数:"+--titck);
}
}finally {
lock.unlock();
}
}
}
}
}
synchronized:隐式锁
1、同步代码块
2、同步方法
jdk1.5之后:显示锁
3、同步锁Lock
注意:是一个显示锁,需要通过lock()方法上锁,必须通过unlock()方法进行释放锁。
评论 (0)