package ThreadTest.Day3;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author CCQ
* Lock是一个接口,ReentrantLock是这个接口的一个实现类
* lock();加锁
* unlock();解锁,加锁后记得解锁
* 使用lock锁
*/
public class Test05 {
public static void main(String[] args) {
TestLock testLock =new TestLock();
new Thread(testLock,"棋棋").start();
new Thread(testLock,"瑶瑶").start();
new Thread(testLock,"婠婠").start();
}
}
class TestLock implements Runnable{
static int num =10;
//定义lock锁
private static final ReentrantLock reentrantLock =new ReentrantLock();
@Override
public void run() {
while (true){
try {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
reentrantLock.lock();//加锁
if (num>0){
System.out.println(Thread.currentThread().getName()+num--);
}else
break;
}finally {
reentrantLock.unlock();//解锁
}
}
}
}
Lock锁初尝试
最新推荐文章于 2022-08-02 06:18:23 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)