1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.sympa.lesson01;
import java.util.concurrent.locks.ReentrantLock;
public class Tickets01 {
public static void main(String[] args){ Tickets tickets = new Tickets(); new Thread(tickets, "黄牛1号").start(); new Thread(tickets, "黄牛2号").start(); new Thread(tickets, "黄牛3号").start(); } } class Tickets implements Runnable{
private int ticket = 10; boolean flag = true; private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while(flag) { buy(); } }
public void buy() { try{ lock.lock(); if(ticket == 0) { flag = false; return; } System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- + "张票"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } finally { lock.unlock(); } } }
|