Untitled
unknown
plain_text
a year ago
16 kB
1
Indexable
Never
package org.example.Model; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class Server implements Runnable { private BlockingQueue<Task> tasks; private AtomicInteger waitingPeriod; public int getIdSer() { return idSer; } public void setIdSer(int idSer) { this.idSer = idSer; } private int idSer=0; public Server() { // initialize queue and waitingPeriod tasks = new LinkedBlockingQueue<Task>(); waitingPeriod = new AtomicInteger(0); } public void setTasks(LinkedBlockingQueue<Task> tasks) { this.tasks = tasks; } public Integer getWaitingPeriod() { return waitingPeriod.get(); } public void setWaitingPeriod(AtomicInteger waitingPeriod) { this.waitingPeriod = waitingPeriod; } public void addTask(Task newTask) { // add task to queue tasks.add(newTask); //newTask.setFinalTime(); // increment the waitingPeriod waitingPeriod.getAndAdd(newTask.getServiceTime()); } public BlockingQueue<Task> getTasks() { return tasks; } @Override public void run() { while (true) { try { // Get the first task in the queue without removing it Task firstTask = tasks.peek(); if (firstTask != null) { // Process the task Thread.sleep(1000); firstTask.setServiceTime(firstTask.getServiceTime()-1); // Remove the task from the queue if(firstTask.getServiceTime() == 0) {tasks.take(); } // Update the waiting period of the server this.waitingPeriod.getAndDecrement(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } package org.example.Model; public class Task extends Thread{ private int ID;//id client private int serviceTime;//timp de procesare private int arrivalTime; public Task (int ID,Integer arrivalTime,Integer serviceTime){ this.ID=ID; this.arrivalTime=arrivalTime; this.serviceTime=serviceTime; } public int getID() { return ID; } public void setID(int ID) { this.ID = this.ID; } public int getArrivalTime() { return arrivalTime; } public void setArrivalTime( int arrivalTime) { this.arrivalTime = arrivalTime; } public int getServiceTime() { return serviceTime; } public void setServiceTime( int serviceTime) { this.serviceTime = serviceTime; } @Override public String toString() { return "("+ ID + ", " + arrivalTime + ", " + serviceTime+ ")"; } } package org.example.BusinessLogic; import org.example.BusinessLogic.Strategy; import org.example.Model.Server; import org.example.Model.Task; import java.util.List; public class ConcreteStrategyQueue implements Strategy { public void addTask(List<Server> servers, Task task) { int min = 10000; Server minServer = null; for (Server s : servers) { if (s.getTasks().size() < min) { min = s.getTasks().size(); minServer = s; } } minServer.addTask(task); } } package org.example.BusinessLogic; import org.example.Model.Server; import org.example.Model.Task; import java.util.List; interface Strategy { public void addTask(List<Server> servers, Task task); } public class ConcreteStrategyTime implements Strategy { @Override public void addTask(List<Server> servers, Task t) { int min = 1000; int serverId = 0; for (int i = 0; i < servers.size(); i++) { Server s = servers.get(i); if (s.getWaitingPeriod() < min) { min = s.getWaitingPeriod(); serverId = i; } } if (serverId != -1) { servers.get(serverId).addTask(t); } } } enum SelectionPolicy{ SHORTEST_QUEUE,SHORTEST_TIME; } package org.example.BusinessLogic; import org.example.BusinessLogic.ConcreteStrategyQueue; import org.example.BusinessLogic.ConcreteStrategyTime; import org.example.BusinessLogic.SelectionPolicy; import org.example.BusinessLogic.Strategy; import org.example.Model.Server; import org.example.Model.Task; import java.util.ArrayList; import java.util.List; public class Scheduler { private List<Server> servers=new ArrayList<>(); private int maxNoServers; private int maxTasksPerServer; private Strategy strategy; public List<Server> getServers() { return servers; } public void setServers(List<Server> servers) { this.servers = servers; } public int getMaxNoServers() { return maxNoServers; } public void setMaxNoServers(int maxNoServers) { this.maxNoServers = maxNoServers; } public int getMaxTasksPerServer() { return maxTasksPerServer; } public void setMaxTasksPerServer(int maxTasksPerServer) { this.maxTasksPerServer = maxTasksPerServer; } public Strategy getStrategy() { return strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public Scheduler(int maxNoServers, int maxTasksPerServer) { this.maxNoServers = maxNoServers; servers = new ArrayList<Server>(); // for each server for (int i = 0; i < maxNoServers; i++) { // create a new Server object Server server = new Server(); server.setIdSer(i); // create a new thread with the Server object and start it Thread thread = new Thread(server); // add the Server object to the list of servers servers.add(server); thread.start(); } changeStrategy(SelectionPolicy.SHORTEST_TIME); } public void changeStrategy(SelectionPolicy selectionPolicy) { // apply strategy pattern to instantiate the strategy with the concrete strategy corresponding to policy if (selectionPolicy == SelectionPolicy.SHORTEST_QUEUE) { strategy = new ConcreteStrategyQueue(); } if (selectionPolicy == SelectionPolicy.SHORTEST_TIME) { strategy = new ConcreteStrategyTime(); } } public void dispatchTask(Task task) { // call the strategy addTask method to add the task to the appropriate server strategy.addTask(servers, task); } } package org.example.BusinessLogic; //import GUI.SimulationFrame; import org.example.Model.Server; import org.example.Model.Task; //import GUI.SimulationFrame; import java.io.*; import java.util.*; public class SimulationManager implements Runnable { //data read from UI // private SimulationFrame frame; private List<Task> tasks; public int timeLimit;//maximum proccesing time -read from UI public int maxProcessingTime; public int minProcessingTime; public int minArrivalTime; public int maxArrivalTime; public int numberOfServers; public int getNumberOfClients; public int currentTime = 0; private SelectionPolicy selectionPolicy = SelectionPolicy.SHORTEST_TIME; //entity responsible with queue management and client distribution private Scheduler scheduler; //frame for displaying simulation // private SimulationFrame frame; // pool of tasks(client shopping in the store) private List<Task> generatedTasks; public float averageServiceTime; public String text; //initialize the scheduler //create and start numberOfServers threads //initialize selection strategy //=>createStrategy //initialize frame to display simulation //generate numberOfClients clients using generateNRandomTasks() //and store them to generatedTasks public SimulationManager(int N, int Q, int tMax, int tMinArrival, int tMaxArrival, int tMinService, int tMaxService) { this.getNumberOfClients = N; this.numberOfServers = Q; this.timeLimit = tMax; this.minArrivalTime = tMinArrival; this.maxArrivalTime = tMaxArrival; this.minProcessingTime = tMinService; this.maxProcessingTime = tMaxService; this.text=""; this.scheduler = new Scheduler(numberOfServers, getNumberOfClients); generatedTasks = Collections.synchronizedList(new ArrayList<Task>()); generateNRandomTasks( N, tMinArrival,tMaxArrival, tMinService, tMaxService); } // this.frame = new SimulationFrame(); // setValues(frame.getInitValues()); private void generateNRandomTasks(int N, int minArrivalTime, int maxArrivalTime, int minProcessingTime, int maxProcessingTime) { int idClient=1; for (int i = 0; i < N; i++) { Random random = new Random(); int arrivalTime = random.nextInt(maxArrivalTime - minArrivalTime + 1) + minArrivalTime; int processingTime = random.nextInt(maxProcessingTime - minProcessingTime + 1) + minProcessingTime;//service // averageServiceTime += processingTime; Task task = new Task(idClient, arrivalTime, processingTime); System.out.println(task); idClient++; this.generatedTasks.add(task); } generatedTasks.sort(new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { return Integer.compare(t1.getArrivalTime(), t2.getArrivalTime()); } }); } public void writeText(){ text+="Time "+currentTime; text+="\n"; text+="Waiting Clients: "; for (Task c:generatedTasks){ text+=c.toString(); } text+="\n"; for(Server s:scheduler.getServers()){ text+="Queue"+" "+(s.getIdSer()+1)+":"; if(s.getTasks().size()!=0){ for(Task t1:s.getTasks()){ text+= t1.toString(); } } else text+="closed"; text+="\n"; } text+="\n"; } public void run() { while (currentTime < timeLimit) { boolean finished = true; // System.out.println("Time: " + currentTime); while (finished) { if (generatedTasks.size() > 0) { Task firstTask = generatedTasks.get(0); if (firstTask.getArrivalTime() == currentTime) { scheduler.dispatchTask(firstTask); generatedTasks.remove(firstTask); } else if (firstTask.getArrivalTime() > currentTime) { finished = false; } } if (generatedTasks.size() == 0) { finished = false; } } for (Task generatedTask : generatedTasks) { //System.out.println(generatedTask.getID() + " " + generatedTask.getArrivalTime() + " " + generatedTask.getServiceTime()); } writeText(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } currentTime++; try { FileWriter fileWriter = new FileWriter("prezentare1.txt"); fileWriter.write(text); fileWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public static void main(String[] args) { int numberOfServers = 5; int numberOfClients = 40; int timeLimit = 30; int minArrivalTime = 2; int maxArrivalTime = 28; int minProcessingTime = 3; int maxProcessingTime = 9; SimulationManager gen = new SimulationManager(numberOfClients,numberOfServers,timeLimit,minArrivalTime,maxArrivalTime,minProcessingTime,maxProcessingTime); Thread t = new Thread(gen); t.start(); } } package org.example.BusinessLogic; import org.example.Model.Server; import org.example.Model.Task; import java.util.List; public interface TimeStrategy { public void addTask(List<Server>servers, Task task); } package org.example.GUI; import javax.swing.*; import java.awt.*; public class SimulationFrame { JFrame frame = new JFrame("Simulation Frame"); JPanel panel = new JPanel(); JPanel panel1 = new JPanel(); JLabel nrOfClients = new JLabel("Nr. clients:"); JTextField nrOfClientsText = new JTextField(10); JPanel panel2 = new JPanel(); JLabel nrOfServers = new JLabel("Nr. servers:"); JTextField nrOfServersText = new JTextField(10); JPanel panel3 = new JPanel(); JLabel timeLimit = new JLabel("Time Limit:"); JTextField timeLimitText = new JTextField(10); JPanel panel4 = new JPanel(); JLabel arrivalTime = new JLabel("Arrival time:"); JTextField minArrivalTimeText = new JTextField(10); JTextField maxArrivalTimeText = new JTextField(10); JPanel panel5 = new JPanel(); JLabel serviceTime = new JLabel("Service Time:"); JTextField minServiceTimeText = new JTextField(10); JTextField maxServiceTimeText = new JTextField(10); JButton startButton = new JButton("START"); JFrame resultsFrame = new JFrame("Simulation Results"); JTextArea resultsArea = new JTextArea(); public SimulationFrame() { frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(500, 350)); frame.setResizable(false); resultsFrame.setMinimumSize(new Dimension(700, 500)); resultsFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); panel.setLayout(new GridLayout(6, 1)); panel1.add(nrOfServers); panel1.add(nrOfServersText); panel2.add(nrOfClients); panel2.add(nrOfClientsText); panel3.add(timeLimit); panel3.add(timeLimitText); panel4.add(arrivalTime); panel4.add(minArrivalTimeText); panel4.add(maxArrivalTimeText); panel5.add(serviceTime); panel5.add(minServiceTimeText); panel5.add(maxServiceTimeText); panel.add(panel1); panel.add(panel2); panel.add(panel3); panel.add(panel4); panel.add(panel5); panel.add(startButton); frame.add(panel); frame.setVisible(true); resultsFrame.add(resultsArea); } public static void main(String[] args) { new SimulationFrame(); } }