请回顾 第六章第8节 原子变量
在本节中,将学习如何扩展一个原子对象,如何遵循原子对象保证所有操作一步完成的机制来实现2个操作。
本节的示例代码在 com.elanzone.books.noteeg.chpt7.sect11 package中
ParkingCounter 类 : extends AtomicInteger
private int maxNumber; public ParkingCounter(int maxNumber) { set(0); this.maxNumber = maxNumber; }
public boolean carIn() { for (; ; ) { int value = get(); if (value == maxNumber) { System.out.printf("ParkingCounter: The parking lot is full.\n"); return false; } else { int newValue = value + 1; boolean changed = compareAndSet(value, newValue); if (changed) { System.out.printf("ParkingCounter: A car has entered.\n"); return true; } } } }
public boolean carOut() { for (; ; ) { int value = get(); if (value == 0) { System.out.printf("ParkingCounter: The parking lot is empty.\n"); return false; } else { int newValue = value - 1; boolean changed = compareAndSet(value, newValue); if (changed) { System.out.printf("ParkingCounter: A car has gone out.\n"); return true; } } } }
Runnable 实现类: Sensor1
private ParkingCounter counter; public Sensor1(ParkingCounter counter) { this.counter = counter; }
@Override public void run() { counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carOut(); counter.carOut(); counter.carOut(); counter.carIn(); counter.carIn(); counter.carIn(); }
Runnable 实现类 : Sensor2 : 和 Sensor1 类似
public class Sensor2 implements Runnable { private ParkingCounter counter; public Sensor2(ParkingCounter counter) { this.counter = counter; } @Override public void run() { counter.carIn(); counter.carOut(); counter.carOut(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); } }
控制类 : Main
public static void main(String[] args) throws Exception { ParkingCounter counter = new ParkingCounter(5); Sensor1 sensor1 = new Sensor1(counter); Sensor2 sensor2 = new Sensor2(counter); Thread thread1 = new Thread(sensor1); Thread thread2 = new Thread(sensor2); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.printf("Main: Number of cars: %d\n", counter.get()); System.out.printf("Main: End of the program.\n"); }
ParkingCounter 类以 2 个原子操作(carIn() 和 carOut())扩展 AtomicInteger 类。 本例模拟一个控制一个停车场内汽车数量的系统。停车场可进入一定数量的汽车,由 maxNumber 属性代表。
carIn() 操作把停车场内汽车的实际数量与最大值比较。 如果相等,汽车不能进入停车场,方法返回 false;否则使用原子操作的以下结构:
carOut() 方法和 carIn() 方法相似。
还实现了2个 Runnable 对象使用 carIn() 和 carOut() 方法来模拟停车活动。 当您执行此程序,您能看到停车场中停车数永不会超过最大停车数。