您的位置:首页 > 其它

【华为2014上机试题】设计一个定时器管理系统

2014-09-21 00:00 429 查看
摘要: http://www.oschina.net/question/1240721_172534 原址

junit启动 :

@Test
public void testTimerManager() throws IOException{
TimerManager manager=new TimerManager();
manager.execut();
}

=====================逻辑部分================================

package org.gradle;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Charsets;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.StandardSystemProperty;
import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.io.Files;
import com.google.common.io.LineReader;

public class TimerManager {
private volatile boolean running=false;
private List<ScheduledTask> scheduledTasks;
private ScheduledExecutorService executor;
private File targetFile=new File("F:/下载/caowei/caowei.txt");
private File targetFile1=new File("F:/下载/caowei/caowei1.txt");
public TimerManager() {
if(targetFile.exists()){
try {
Files.write("", targetFile, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
running=true;
scheduledTasks=Lists.newCopyOnWriteArrayList();
executor=Executors.newScheduledThreadPool( Runtime.getRuntime().availableProcessors());
executor.submit(new Runnable() {
public void run() {
if(targetFile1.exists()){
try {
Files.write("", targetFile1,Charsets.UTF_8);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (running) {
Iterator<ScheduledTask> iterator=scheduledTasks.iterator();
StringBuilder sb=new StringBuilder();
while (iterator.hasNext()) {
ScheduledTask task=iterator.next();
sb.append("timer:").
append(task.getId()).
append(",").append(task.limit-task.stopwatch.elapsed(TimeUnit.MILLISECONDS)).
append(StandardSystemProperty.LINE_SEPARATOR.value());;
}
if(Iterables.size(scheduledTasks)==0){
sb.delete(0, sb.length());
sb.append("none").append(StandardSystemProperty.LINE_SEPARATOR.value());
}
try {
Files.write(sb.toString(), targetFile1, Charsets.UTF_8);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public void execut() throws IOException {
LineReader leLineReader=new LineReader(new InputStreamReader(System.in));
while (running) {
String str=leLineReader.readLine();
if(Strings.isNullOrEmpty(str)){
continue;
}
Iterable<String> it= Splitter.onPattern("(:|,)").omitEmptyStrings().trimResults().split(str);
String command=Iterables.get(it, 0);
if(str.equals("end")){
running=false;
executor.shutdown();
}else if("starttimmer".equals(command)){
ScheduledTask scheduledTask=new ScheduledTask(Integer.valueOf(Iterables.get(it, 1)),
Long.valueOf(Iterables.get(it, 2))){
public void run() {
long elapse= getStopwatch().elapsed(TimeUnit.MILLISECONDS);
StringBuilder target=new StringBuilder();
if(elapse>=getLimit()){
target.append("===定时器:id=").append(getId()).append("==停止==").
append(StandardSystemProperty.LINE_SEPARATOR.value());
getFuture().cancel(false);
Iterables.removeIf(scheduledTasks,new Predicate<ScheduledTask>() {
public boolean apply(ScheduledTask input) {
if(input.id==getId()){
if(input.future.cancel(false)){
StringBuilder target=new StringBuilder();
target.append("===定时器:id=").append(input.id).append("==停止==").
append(StandardSystemProperty.LINE_SEPARATOR.value());
try {
Files.append(target.toString(), targetFile, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
return false;
}
});
return;
}
target.append("===定时器:id=").append(getId()).append("=当前时间:").append(System.currentTimeMillis()).
append("====").
append(StandardSystemProperty.LINE_SEPARATOR.value());
try {
Files.append(target.toString(), targetFile, Charsets.UTF_8);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
scheduledTask.future=executor.scheduleAtFixedRate(scheduledTask, 10, scheduledTask.fixedRate,
TimeUnit.MILLISECONDS);
if(scheduledTask.future!=null){
scheduledTask.stopwatch=Stopwatch.createStarted();
scheduledTask.startTimeMillis=System.currentTimeMillis();
}
scheduledTasks.add(scheduledTask);
Ordering<ScheduledTask> ordering= Ordering.from(new Comparator<ScheduledTask>() {
public int compare(ScheduledTask o1, ScheduledTask o2) {
long l= o1.startTimeMillis-o2.startTimeMillis;
if(l>0){
return 1;
}else if(l<0){
return -1;
}else{
return 0;
}
}
});
scheduledTasks=ordering.sortedCopy(scheduledTasks);

}else if("stoptimmer".equals(command)){
final int id=Integer.valueOf(Iterables.get(it,1));
Iterables.removeIf(scheduledTasks,new Predicate<ScheduledTask>() {
public boolean apply(ScheduledTask input) {
if(input.id==id){
if(input.future.cancel(false)){
StringBuilder target=new StringBuilder();
target.append("===定时器:id=").append(input.id).append("==停止==").
append(StandardSystemProperty.LINE_SEPARATOR.value());
try {
Files.append(target.toString(), targetFile, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
return false;
}
});
}else if("elapse".equals(command)){
final int elapse=Integer.valueOf(Iterables.get(it,1));

}else{
System.out.println("default");
}
}
}

private abstract static class ScheduledTask implements Runnable{
private volatile int id=-1;
private long startTimeMillis;
private long fixedRate;
private long limit=TimeUnit.MILLISECONDS.convert(100L, TimeUnit.SECONDS);
private volatile Stopwatch stopwatch;
private ScheduledFuture<?> future;

public ScheduledTask(int id, long fixedRate) {
this.id = id;
this.fixedRate = fixedRate;
}
public ScheduledFuture<?> getFuture() {
return future;
}
public long getFixedRate() {
return fixedRate;
}
public int getId() {
return id;
}
public Stopwatch getStopwatch() {
return stopwatch;
}
public long getLimit() {
return limit;
}
public void setStartTimeMillis(long startTimeMillis) {
this.startTimeMillis = startTimeMillis;
}
}

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