package com.mutilthread.executor.battery;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* 例子:电池充电
* 1. 类不可变性(一个精心构造的对象能够保证在其没能恢复到有效状态时,它本身的任何方法都不能够被访问。)
* 2. 多用线程池,不要随意开启线程
* 3. 对可变字段的修改要对多线程访问可见
* 4. 确定锁的粒度
* 5. 确保多个字段变量访问是原子的
* @author yQuery
*
*/
public class RefreshBattery {
private final long MAXLEVEL = 100;
private AtomicLong level = new AtomicLong(MAXLEVEL);
private final static ScheduledExecutorService service =
Executors.newScheduledThreadPool(1, new java.util.concurrent.ThreadFactory(){
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
private ScheduledFuture<?> refresh;
private RefreshBattery() {
}
private void init() {
refresh = service.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
refresh();
}
}, 0, 1, TimeUnit.SECONDS);
}
public static RefreshBattery getInstance() {
RefreshBattery rb = new RefreshBattery();
rb.init();
return rb;
}
private void refresh() {
if(level.get() < MAXLEVEL){ level.incrementAndGet();
System.out.println("charging..."); // 充电中...
} else {
refresh.cancel(true);
System.out.println("finished");// 充电完成.
}
}
public boolean useEnergy(final long units) {
boolean available = false;
final long currentLevel = level.get();
if(units >= 0 && units <= currentLevel) {
level.compareAndSet(currentLevel, currentLevel-units);
available = true;
System.out.println("useEnergy: "+units);
}
return available;
}
public static void main(String[] args) throws InterruptedException {
RefreshBattery rb = getInstance();
rb.useEnergy(5);
TimeUnit.SECONDS.sleep(10);
}
/**
* Output:
* useEnergy: 5
charging...
charging...
charging...
charging...
charging...
finished
*/
}
Java多线程之ScheduledExecutorService
最新推荐文章于 2024-09-03 21:58:45 发布
本文详细介绍了Java中的ScheduledExecutorService,它是多线程处理中的重要工具,用于定时和周期性执行任务。内容涵盖ScheduledExecutorService的基本使用、线程池配置、延迟任务与定时任务的实现,以及如何取消和关闭任务。通过实例分析,深入理解其工作原理和最佳实践。
摘要由CSDN通过智能技术生成