本文主要是介绍Java实现先来先服务与短作业优先,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、定义作业类
package com.ghs.job;
public class Job {/**作业编号*/private String jobId;/**运行时间*/private int runTime;public Job() {super();}public Job(String jobId, int runTime) {super();this.jobId = jobId;this.runTime = runTime;}public int getRunTime() {return runTime;}public void setRunTime(int runTime) {this.runTime = runTime;}public void excute(){System.out.println("作业"+jobId+"正在运行!");}
}
2、定义调度策略
package com.ghs.job;public enum ScheduleStrategy {FCFS, //先来先服务SJF, //短作业优先
}
3、实现调度
实现原理:定义一个调度进程ScheduleThread,不停的访问作业队列,如果队列不为空,就按照调度策略取得下一个需要执行的作业。
注意:由于往作业队列中添加作业和从作业队列中取作业是在两个线程内完成,所以需要加为作业队列加同步锁。
package com.ghs.job;import java.util.Collections;
import java.util.LinkedList;
import java.util.List;public class ScheduleService {private ScheduleStrategy strategy;private ScheduleThread scheduleThread = null;List<Job> jobs= Collections.synchronizedList(new LinkedList<Job>());public ScheduleService() {scheduleThread = new ScheduleThread();scheduleThread.start();}public ScheduleThread getScheduleThread() {return scheduleThread;}public void setScheduleThread(ScheduleThread scheduleThread) {this.scheduleThread = scheduleThread;}public void process(Job job){synchronized (jobs) {jobs.add(job);}}/*** 按照调度策略获取下一个要执行的作业* @return*/public Job getNextJob(){Job job = null;switch (strategy) {case FCFS:job = jobs.remove(0);break;case SJF:System.out.println(jobs.size());job = jobs.get(0);for(int i=1;i<jobs.size(); i++){if(jobs.get(i).getRunTime()<job.getRunTime()){job = jobs.get(i);}}jobs.remove(job);break;default:job = jobs.remove(0);break;}return job;}public ScheduleStrategy getStrategy() {return strategy;}public void setStrategy(ScheduleStrategy strategy) {this.strategy = strategy;}/*** 工作线程,用于执行作业* @author liu*/private class ScheduleThread extends Thread{boolean isRunning = true;@Overridepublic void run() {Job job = null;while(isRunning){synchronized (jobs) {if(!jobs.isEmpty()){job = getNextJob();}}if(job!=null){job.excute();job=null;}}}public void stopSchedule(){this.isRunning = false;}}public static void main(String[] args) {ScheduleService service = new ScheduleService();service.setStrategy(ScheduleStrategy.SJF);service.process(new Job("001",18));service.process(new Job("002",13));service.process(new Job("003",15));service.process(new Job("004",8));service.process(new Job("005",5));}
}
完整代码:http://download.csdn.net/detail/u011983531/9211495
这篇关于Java实现先来先服务与短作业优先的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!