a- package ticket.demo;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class SellDemo3 {
- /**
- * 使用lock实现同步卖票程序模拟
- */
- public static void main(String[] args) {
- int ticket = 100;// 设置票的初始值
- final SharedData sd = new SellDemo3().new SharedData(ticket);
- for (int i = 0; i < 3; i++) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (true)
- sd.dec();
- }
- }, "window" + i).start();
- }
- }
- // 使用内部类,实现票的共享和操作
- class SharedData {
- private int ticket;
- private Lock l = new ReentrantLock();// 创建锁
- private SharedData(int ticket) {
- this.ticket = ticket;
- }
- // 卖票
- public void dec() {
- // 实现同步
- l.lock();// 在访问共享数据前就进行同步
- if (ticket > 0) {
- try {
- ticket--;
- System.out.println(Thread.currentThread().getName()
- + "...Ticket = " + ticket);
- } finally {
- l.unlock();
- }
- } else {
- System.out.println("售罄~~");
- System.exit(0);
- }
- }
- }
- }
复制代码
|
|