lab 8.
This commit is contained in:
@@ -46,9 +46,12 @@ class MySemaphoreTest {
|
||||
void testMultipleThreads() throws InterruptedException {
|
||||
final int THREAD_COUNT = 10;
|
||||
final int PERMITS = 3;
|
||||
|
||||
var semaphore = new MySemaphore(PERMITS);
|
||||
|
||||
var startLatch = new CountDownLatch(1);
|
||||
var finishLatch = new CountDownLatch(THREAD_COUNT);
|
||||
|
||||
var concurrentThreads = new AtomicInteger(0);
|
||||
var maxConcurrentThreads = new AtomicInteger(0);
|
||||
|
||||
@@ -57,14 +60,17 @@ class MySemaphoreTest {
|
||||
try {
|
||||
startLatch.await();
|
||||
semaphore.acquire();
|
||||
|
||||
int current = concurrentThreads.incrementAndGet();
|
||||
maxConcurrentThreads.updateAndGet(max -> Math.max(max, current));
|
||||
Thread.sleep(100); // Имитация работы
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
concurrentThreads.decrementAndGet();
|
||||
|
||||
semaphore.release();
|
||||
finishLatch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
@@ -80,22 +86,29 @@ class MySemaphoreTest {
|
||||
var semaphore = new MySemaphore(1);
|
||||
semaphore.acquire();
|
||||
assertEquals(0, semaphore.availablePermits());
|
||||
|
||||
|
||||
var startLatch = new CountDownLatch(1);
|
||||
var doneLatch = new CountDownLatch(1);
|
||||
var thread = new Thread(() -> {
|
||||
try {
|
||||
startLatch.countDown();
|
||||
|
||||
semaphore.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
|
||||
doneLatch.countDown();
|
||||
});
|
||||
|
||||
thread.start();
|
||||
Thread.sleep(100); // Даем время потоку начать ожидание
|
||||
startLatch.await();
|
||||
|
||||
assertTrue(thread.isAlive());
|
||||
assertEquals(0, semaphore.availablePermits());
|
||||
|
||||
semaphore.release();
|
||||
thread.join(1000);
|
||||
doneLatch.await();
|
||||
|
||||
assertFalse(thread.isAlive());
|
||||
assertEquals(0, semaphore.availablePermits());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user