package rejava3.线程;
import java.util.concurrent.locks.ReentrantLock;
public class Lock {
public static void main(String[] args) {
RLock rl=new RLock();
new Thread(rl,"小明").start();
new Thread(rl,"小亮").start();
new Thread(rl,"小天").start();
}
}
class RLock implements Runnable{
public int ticket=10;
//可重入锁
private final ReentrantLock rtl=new ReentrantLock(); //学习别人的写法
@Override
public void run() {
while (true) {
try {
rtl.lock(); //锁住
if(this.ticket<=0){
break;
}
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "获得了第" + this.ticket-- + "个");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
rtl.unlock(); //开锁
}
}
}
}
java线程Lock使用(原理后期补写)
于 2021-10-19 12:10:26 首次发布