您的位置:首页 > 编程语言 > Java开发

Java多线程之ScheduledExecutorService

2013-10-15 01:13 417 查看


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
*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: