多线程之Lock锁

在这里插入图片描述ReentrantLock:可重入锁
在这里插入图片描述代码:

package com.qiu.syn;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();new Thread(testLock2).start();new Thread(testLock2).start();new Thread(testLock2).start();}

}
class TestLock2 implements Runnable{
    int ticketNums =10;//定义Lockprivate final ReentrantLock lock =new ReentrantLock();@Overridepublic void run() {while (true){try {
​                lock.lock();//加锁if (ticketNums>0){try {
​                        Thread.sleep(1000);} catch (InterruptedException e) {
​                        e.printStackTrace();}
​                    System.out.println("票拿到了"+ticketNums--);}else {return;}} finally {//解锁
​                lock.unlock();}}}
}

在这里插入图片描述

原创文章 32 获赞 52 访问量 654

猜你喜欢

转载自blog.csdn.net/qq_42400763/article/details/105740685