1 package day2_4; 2 3 import java.util.concurrent.locks.ReentrantLock; 4 5 /** 6 * 解决线程安全问题方式三:loke锁 ---JDK5.0新增 7 * 8 * 1.面试题:synchronized 与 lock的异同? 9 * 相同:两者都可以解决线程安全问题 10 * 不同:synchronized机制在执行完相应的代码以后,自动的释放同步监视器 11 * lock需要手动的启动同步[lock()] ,也需要手动的结束同步[unlock()] 12 * 13 * 14 * 2.优先使用顺序:Lock -> 同步代码块 -> 同比方法 15 * 16 * 3.如何解决线程安全问题?有几种方式 17 * 18 * @Author Tianhao 19 * @create 2021-02-05-17:18 20 */ 21 22 class Window7 implements Runnable { 23 private int ticket = 100; 24 25 //1.实例化ReentranLock 26 private ReentrantLock lock = new ReentrantLock(); 27 28 @Override 29 public void run() { 30 31 while (ticket > 0) { 32 try { 33 //2.调用锁定方法lock() 34 lock.lock(); 35 if (ticket > 0) { 36 System.out.println(Thread.currentThread().getName() + 37 "卖票,票号:" + ticket); 38 ticket--; 39 } 40 } finally { 41 //3.调用解锁方法 unlock() 42 lock.unlock(); 43 } 44 Thread.currentThread().yield(); 45 } 46 } 47 } 48 49 50 public class WindowTest7 { 51 public static void main(String[] args) { 52 Window7 w = new Window7(); 53 Thread t1 = new Thread(w); 54 Thread t2 = new Thread(w); 55 Thread t3 = new Thread(w); 56 t1.setName("窗口1"); 57 t2.setName("窗口2"); 58 t3.setName("窗口3"); 59 t1.start(); 60 t2.start(); 61 t3.start(); 62 63 } 64 }