package lock; /* 方式三: Lock锁 synchronized和lock的不同 1.sychronized在执行完相应代码块以后属于自动释放同步监视器,lock需要手动启动同步 建议优先使用lock->同步方法块->同步方法(在方法体之外) 实现Runnable对象被三个线程调用,然后这个对象的run方法里贡献资源操作器被lock上锁了 @author zsben @create 2020-01-03 23:55 */ import java.util.concurrent.locks.ReentrantLock; class Window implements Runnable{ private int ticket = 100; //1.实例化lock private ReentrantLock lock = new ReentrantLock(true);//fair=true:公平锁,线程先来后到 @Override public void run() { while(true){ try{ //2.调用lock方法 lock.lock(); if(ticket>0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+": "+ticket); ticket--; }else break; } finally { //3.调用解锁方法 lock.unlock(); } } } } public class LockTest { public static void main(String[] args) { Window w = new Window(); Thread t1 = new Thread(w); Thread t2 = new Thread(w); Thread t3 = new Thread(w); t1.start(); t2.start(); t3.start(); } }
原文地址:https://www.cnblogs.com/zsben991126/p/12148326.html
时间: 2024-10-08 10:34:26