1 package bytezero.deadlock; 2 3 import java.util.concurrent.locks.ReentrantLock; 4 5 /** 6 * 解决线程安全问题的方式三:Lock锁 --------jdk 5.0 新增 7 * 8 * 1.面试题:synchronized 与 lock的异同? 9 * 同: 二者都可以解决线程安全问题 10 * 11 * 不同:synchronized 机制在执行完相应的同步代码以后,自动的释放同步监视器 12 * lock需要手动的启动同步(lock()),同时结束同步也需要手动的实现(unlock()) 13 * 14 * 2.如何解决线程安全问题?几种方式 15 * 3种 16 * 17 * 18 * @author Bytezero1·zhenglei! Email:420498246@qq.com 19 * create 2021-10-18 11:03 20 */ 21 class Window implements Runnable{ 22 private int ticket = 100; 23 24 //1.实例化 ReentrantLock 25 private ReentrantLock lock = new ReentrantLock(); 26 27 28 @Override 29 public void run() { 30 while(true){ 31 try { 32 33 //调用lock锁定方法 34 lock.lock(); 35 if(ticket > 0){ 36 try { 37 Thread.sleep(100); 38 } catch (InterruptedException e) { 39 e.printStackTrace(); 40 } 41 42 System.out.println(Thread.currentThread().getName() +": 售票,票号为:" +ticket); 43 ticket--; 44 }else{ 45 break; 46 } 47 }finally { 48 //3.调用解锁的方法 49 lock.unlock(); 50 } 51 } 52 } 53 } 54 public class LockTest { 55 public static void main(String[] args) { 56 Window w1; 57 w1 = new Window(); 58 59 Thread t1 = new Thread(w1); 60 Thread t2 = new Thread(w1); 61 Thread t3 = new Thread(w1); 62 63 t1.setName("窗口一"); 64 t2.setName("窗口二"); 65 t3.setName("窗口三"); 66 67 t1.start(); 68 t2.start(); 69 t3.start(); 70 71 } 72 }
................