其他分享
首页 > 其他分享> > 二十四、锁(Lock)

二十四、锁(Lock)

作者:互联网

public class ThreadLock implements Runnable{

    private int ticket=10;

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            //加锁
            lock.lock();
            while (true){
                if (ticket>0){
                    System.out.println(Thread.currentThread().getName()+"买到的票号:"+ticket--);
                }else{
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //解锁
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ThreadLock t = new ThreadLock();
        new Thread(t,"张三").start();
        new Thread(t,"李四").start();
        new Thread(t,"王五").start();
    }
}

 

标签:ReentrantLock,Thread,lock,二十四,线程,Lock,new
来源: https://www.cnblogs.com/epiphany8/p/16272166.html