首页 > 其他分享 >lock锁

lock锁

时间:2023-03-19 11:12:24浏览次数:30  
标签:Thread lock ReentrantLock start new public

package edu.wtbu;

import java.util.concurrent.locks.ReentrantLock;

public class Demo01 {
public static void main(String[] args) {
Lock lock = new Lock();
new Thread(lock).start();
new Thread(lock).start();
new Thread(lock).start();
}

}
class Lock implements Runnable{
int ticketNums=10;

//定义lock锁
private final ReentrantLock lock=new ReentrantLock();//ReentrantLock:可重入锁

@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if(ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(ticketNums--);
}else{
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}

标签:Thread,lock,ReentrantLock,start,new,public
From: https://www.cnblogs.com/123456dh/p/17232612.html

相关文章