其他分享
首页 > 其他分享> > 可重用锁

可重用锁

作者:互联网

 

查看代码

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();//解锁
            }
        }
    }
}

 

标签:testLock1,Thread,lock,重用,start,TestLock1,new
来源: https://www.cnblogs.com/evelei/p/16141735.html