标签:
本例子为电池使用和充电,并计算使用次数,可见性、增强高并发、保证原子性
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class EnergySourceFinal { private final long MAXLEVEL = 100; private AtomicLong level = new AtomicLong(MAXLEVEL);//保证了多线程并发访问环境下的可见性和线程安全性,在本例中可改为long类型 private long usage = 0; private ReadWriteLock monitor = new ReentrantReadWriteLock();//原子性 //执行周期性任务 //private static ScheduledExecutorService replenishTimer = Executors.newScheduledThreadPool(10); private static ScheduledExecutorService replenishTimer = Executors.newScheduledThreadPool(10,new ThreadFactory() { public Thread newThread(Runnable arg0) { Thread thread = new Thread(arg0); return thread; } });//ThreadFactory能保证所创建的所有线程都是守护线程 ScheduledFuture<?> replenishTask; public EnergySourceFinal() { } private void init() { replenishTask = replenishTimer.scheduleAtFixedRate(new Runnable() { public void run() { replenish(); } }, 0, 1, TimeUnit.SECONDS); } private void replenish() { monitor.writeLock().lock();//写锁 try{ if(level.get() < MAXLEVEL) { level.getAndIncrement(); System.out.println("充电中:"+level.get()); } }finally{ monitor.writeLock().unlock(); } } //不要在构造函数中启动线程,避免线程在对象尚未构造完成之前就调用其成员方法,建议使用静态工厂函数 public static EnergySourceFinal create() { final EnergySourceFinal energySource = new EnergySourceFinal(); energySource.init(); return energySource; } //synchronized 竞争条件下保证可见性 public synchronized void stopEnergySource() { replenishTask.cancel(false); } public boolean useEnergy(final long units) { monitor.writeLock().lock(); try{ long currentLevel = level.get(); if(currentLevel > units && units > 0) { level.compareAndSet(currentLevel, currentLevel-units); System.out.println("使用"+units+"units"); return true; } return false; }finally{ monitor.writeLock().unlock(); } } public long getUnitsAvailable() { monitor.readLock().lock(); try { return level.get(); } finally { monitor.readLock().unlock(); } } public long getUsageCount() { monitor.readLock().lock();//读锁 try { return usage; } finally { monitor.readLock().unlock(); } } public static void main(String[] args) { final EnergySourceFinal energySource = EnergySourceFinal.create(); new Thread(new Runnable(){ public void run() { energySource.useEnergy(10); } }).start(); new Thread(new Runnable(){ public void run() { energySource.useEnergy(20); } }).start(); new Thread(new Runnable(){ public void run() { energySource.useEnergy(10); } }).start(); for(long i = 0; i < 20000000000l; i++) { if(i == 15999999999l) System.out.println("当前值:"+energySource.getUnitsAvailable()); } } }
标签:
原文地址:http://www.cnblogs.com/hellocyc/p/4285951.html