可重用锁

 

查看代码

package com.lei.study03;

import java.util.concurrent.locks.ReentrantLock;

//测试lock锁
public class TestLock {
    public static void main(String[] args) {
        TestLock1 testLock1 = new TestLock1();

        new Thread(testLock1,"A").start();
        new Thread(testLock1,"B").start();
        new Thread(testLock1,"C").start();
    }
}

class TestLock1 implements Runnable{

    int tickNums=10;

    //定义可重用锁
    ReentrantLock lock=new ReentrantLock();

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

 

posted @ 2022-04-13 19:20  Eveeee  阅读(51)  评论(0)    收藏  举报