线程二十一—— 加锁

注意: private final ReentrantLock lock= new ReentrantLock(); 加锁使用的类 对线程的实现不仅要加索,还要解锁。所以我们一般使用try catch finally 表达式,加锁放在try块中,解锁放在finally中

package com.yyf.Gaoji;

import java.util.concurrent.locks.ReentrantLock;

public class AddLock {
    public static void main(String[] args) {
        TestAddLock t1 = new TestAddLock ();
         new Thread (t1).start ();
         new Thread (t1).start ();
         new Thread (t1).start ();
    }
}
class TestAddLock implements Runnable{
 int ticketNum=10;
    private final  ReentrantLock lock=  new ReentrantLock();
    @Override
    public void run() {
        while(true){
            try{
                lock.lock ();
                if (ticketNum>0) {
                    Thread.sleep (1000);
                    System.out.println (Thread.currentThread ().getName () + "拿到了第" + ticketNum-- + "张票");
                }else{
                    break;
                }
            }catch (Exception e){
               e.printStackTrace ();
            }finally {
                lock.unlock ();
            }
        }
    }
}
经验分享 程序员 微信小程序 职场和发展