Lock锁解决线程安全 -----> JDK5.0新增
作者:互联网
import java.util.concurrent.locks.ReentrantLock; // 测试 public class LockTest { public static void main(String[] args) { Windows w = new Windows(); Thread t1 = new Thread(w); Thread t2 = new Thread(w); Thread t3 = new Thread(w); t1.setName("窗口一"); t2.setName("窗口二"); t3.setName("窗口三"); t1.start(); t2.start(); t3.start(); } } class Windows implements Runnable{ private int ticket = 100; // 1.实例化ReentrantLock private ReentrantLock lock = new ReentrantLock(); @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.调用解锁方法: unlock() lock.unlock(); } } } }
标签:Thread,Lock,ReentrantLock,start,-----,JDK5.0,lock,new,ticket 来源: https://www.cnblogs.com/lxh-daniel/p/16672182.html