15、lock锁
package com.syn; import java.util.concurrent.locks.ReentrantLock; public class LockBuyTickets { public static void main(String[] args) { BuyTickets buyer = new BuyTickets(); new Thread(buyer,"daliwang").start(); new Thread(buyer,"xiaoliwang").start(); new Thread(buyer,"zhongliwang").start(); } } class BuyTickets implements Runnable{ //票 private int ticketsNum = 10; private final ReentrantLock lock = new ReentrantLock();//定义锁 //循环标志 boolean flag = true; //重写run方法 @Override public void run() { //买票 while(flag){ try{ lock.lock(); buy(); }finally { lock.unlock(); } } } //判断是否有票,增加同步锁 public synchronized void buy(){ if(ticketsNum<=0){ flag=false;//设置停止标志 return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"拿到"+ticketsNum--); } }