【华为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;
}
}
}
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;
}
}
}
相关文章推荐
- 华为机试-设计一个定时器管理系统
- 一个资源管理系统的设计--基于cgroup机制
- 我设计的一个基于RBAC模型的通用权限管理系统的域模型类图
- 一个简洁的CMS系统管理界面设计
- 2014华为武汉上机试题二:姓名的夫妻相
- 2014华为武汉上机试题一:手机电池余量
- 2014华为武汉上机试题一:手机电池余量
- 2013华为实习生上机考试试题(一)华为机试 请设计函数int getTest(char input[]) ,检测输入字符串中是否包含连续的或者离散的test,test只出现一次
- 2014华为武汉上机试题三:CandyBrush游戏
- 基于VC++6.0系统设计一个小型的信息管理应用程序。如航空订票系统、学生管理系统、图书管理系统,学生自选的项目等。
- dr-helper项目设计介绍(一个包含移动端和Web端的点餐管理系统)
- 一个资源管理系统的设计--解析linux的cgroup实现
- 自己设计的一个亲自活动报名管理系统数据库
- 设计一个图书借阅管理系统需要如何分析
- 如何设计一个设备管理系统平台?-之 一 :背景概述
- 一个学生成绩管理系统的设计与实现:2
- 歌厅歌曲管理系统(转)用c语言实现的一个课程设计
- 分享一个大一的课程设计,学校新闻系统——新闻管理模块
- DTCC2014:非结构化大数据管理系统的设计及其应用案例-李银松
- 2014华为上机试题