Заготовка планировщика.

This commit is contained in:
2023-09-26 22:57:18 +03:00
parent 6df3eb05ee
commit 0026701347
5 changed files with 118 additions and 7 deletions

View File

@@ -0,0 +1,81 @@
package SapforTestingSystem.ThreadsPlanner;
import Common.Global;
import Common.Utils.InterruptThread;
import java.util.LinkedHashMap;
import java.util.Vector;
public abstract class ThreadsPlanner {
//-->
Thread interruptThread = new InterruptThread(5000, () -> {
System.exit(0);
return null;
});
protected int maxKernels;
protected int kernels;
//---
protected int threadMaxId = 0;
protected int wait_ms;
protected LinkedHashMap<Integer, Thread> threads = new LinkedHashMap<>();
protected Vector<Integer> activeThreads = new Vector<>();
protected Vector<Integer> waitingThreads = new Vector<>();
//--
public ThreadsPlanner(int wait_ms_in, int maxKernels_in) {
wait_ms = wait_ms_in;
maxKernels = maxKernels_in;
kernels = maxKernels;
}
//--
public void Start() {
Global.Log.Print("Planner started");
try {
//--
while (!waitingThreads.isEmpty() || !activeThreads.isEmpty()) {
Global.Log.Print("Waiting: " + waitingThreads.size() + "; Running: " + activeThreads.size() + ".");
checkActiveThreads();
tryStartThreads();
Thread.sleep(wait_ms);
}
//--
} catch (Exception exception) {
exception.printStackTrace();
Global.Log.PrintException(exception);
}
Global.Log.Print("Planner finished");
finalize();
}
protected void checkActiveThreads() throws Exception {
Vector<Integer> toExclude = new Vector<>();
//--
for (int i : activeThreads) {
Thread thread = threads.get(i);
if (!thread.isAlive()) {
toExclude.add(i);
kernels++;
}
}
activeThreads.removeAll(toExclude);
//--
}
protected void tryStartThreads() throws Exception {
Vector<Integer> toExclude = new Vector<>();
//-
for (int i : waitingThreads) {
if (kernels > 0) {
Thread thread = threads.get(i);
thread.start();
activeThreads.add(i);
kernels--;
toExclude.add(i);
} else break;
}
waitingThreads.removeAll(toExclude);
}
protected void finalize() {
}
protected void addThread(Runnable runnable) {
Thread thread = new Thread(runnable);
threads.put(threadMaxId, thread);
waitingThreads.add(threadMaxId);
threadMaxId++;
}
}