1. 程式人生 > >Java實現先來先服務與短作業優先

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; @Override public 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)); } }