ReentrantLock的简单使用

import java.util.concurrent.locks.ReentrantLock;
// 线程 操作资源库
class Tickets {
    private int nums = 30;
    ReentrantLock lock = new ReentrantLock();
    public void scale(){
        lock.lock();
        try {
            if (nums>0){
                for (int i = 30; i > 0; i--) {
                    nums--;
                    System.out.println(Thread.currentThread().getName() + i);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }
}

public class lock {
    public static void main(String[] args) {
        Tickets t = new Tickets();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                t.scale();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                t.scale();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                t.scale();
            }
        }).start();


    }

}

posted @ 2020-08-04 22:27  z_先生  阅读(163)  评论(0编辑  收藏  举报