Вынес функции для сна потоков в Utils

This commit is contained in:
2025-02-11 12:42:28 +03:00
parent aef1113061
commit ee8988056a
4 changed files with 24 additions and 25 deletions

View File

@@ -33,16 +33,7 @@ public class Heater implements Runnable {
while (!Thread.interrupted()) {
if (isOn) room.adjustTemperature(random.nextDouble() * temperatureMaxStep);
try {
Thread.sleep(getStepTime());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Utils.sleepRandomTime((long) (maxStepTimeMs * 0.5), maxStepTimeMs);
}
}
}
private long getStepTime() {
// Спим от 0.5 * maxStepTimeMs до maxSteTimeMs миллисекунд
return (long) (random.nextDouble() * 0.5 + 0.5) * maxStepTimeMs;
}
}

View File

@@ -37,16 +37,7 @@ public class Room implements Runnable {
temperature += (random.nextDouble() - 0.5) * 2 * temperatureMaxStep;
humidity += (random.nextDouble() - 0.5) * 2 * humidityMaxStep;
try {
Thread.sleep(getStepTime());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Utils.sleepRandomTime((long) (maxStepTimeMs * 0.5), maxStepTimeMs);
}
}
}
private long getStepTime() {
// Спим от 0.5 * maxStepTimeMs до maxSteTimeMs миллисекунд
return (long) (random.nextDouble() * 0.5 + 0.5) * maxStepTimeMs;
}
}

View File

@@ -40,11 +40,7 @@ public class Sensor implements Runnable {
temperature = room.getTemperature() + (random.nextDouble() - 0.5) * 2 * maxTemperatureError;
humidity = room.getHumidity() + (random.nextDouble() - 0.5) * 2 * maxHumidityError;
try {
Thread.sleep(updateIntervalMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Utils.sleep(updateIntervalMs);
}
}
}

View File

@@ -0,0 +1,21 @@
package ru.spbstu.telematics.java;
import java.util.concurrent.ThreadLocalRandom;
public class Utils {
static public void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static public void sleepRandomTime(long from, long to) {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(from, to));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}