51,397
社区成员




import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class OperationSystem {
private static class Operation {
public enum Type{
Compute, IO
}
private Type type;
private int time;
public Operation(Type type, int time){
this.type = type;
this.time = time;
}
/** @return finished. */
public boolean execute(){
return --time <= 0;
}
}
private static class Process {
private final String name;
private final List<Operation> operations = new ArrayList<>();
public Process(String name,Operation ... operations){
this.name = name;
this.operations.addAll(Arrays.asList(operations));
}
public boolean run(OperationSystem os) {
Operation operation = operations.get(0);
if (operation.type == Operation.Type.IO) {
if (os.tryLock(this)) {
if (operation.execute()){
operations.remove(0);
os.unLock(this);
}
}
} else if (operation.type == Operation.Type.Compute) {
if (operation.execute()){
operations.remove(0);
}
}
return operations.isEmpty();
}
}
private List<Process> runnable = new ArrayList<>();
private List<Process> suspended = new ArrayList<>();
private Process ioLock = null;
private boolean tryLock(Process process) {
if (ioLock == null) {
ioLock = process;
return true;
}
return ioLock == process;
}
private void unLock(Process process) {
ioLock = null;
}
public void init() {
runnable.add(new Process("A", new Operation(Operation.Type.Compute, 20), new Operation(Operation.Type.IO, 30), new Operation(Operation.Type.Compute, 10)));
runnable.add(new Process("B", new Operation(Operation.Type.Compute, 30), new Operation(Operation.Type.IO, 50), new Operation(Operation.Type.Compute, 20)));
runnable.add(new Process("C", new Operation(Operation.Type.Compute, 10), new Operation(Operation.Type.IO, 20), new Operation(Operation.Type.Compute, 10)));
}
public void start() {
for (int time = 1; !runnable.isEmpty() || !suspended.isEmpty(); time++) {
if (!runnable.isEmpty()) {
for (Iterator<Process> iter = runnable.iterator(); iter.hasNext(); ) {
Process process = iter.next();
if (process.run(this)) {
iter.remove();
System.out.println(process.name + " finish time :" + time);
}
}
}
if (!suspended.isEmpty()) {
for (Iterator<Process> iter = suspended.iterator(); iter.hasNext(); ) {
Process process = iter.next();
if (tryLock(process)) {
iter.remove();
runnable.add(process);
}
}
}
}
}
public static void main(String[] args) {
OperationSystem os = new OperationSystem();
os.init();
os.start();
}
}