@dan_farrell
JUnit предоставляет несколько возможностей для тестирования многопоточного кода. Рассмотрим некоторые из них.
Пример:
1 2 3 4 5 |
@Test @Timeout(5) public void testMultiThreadedCode() throws InterruptedException { // Your code here } |
Пример:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void testMultiThreadedCode() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); new Thread(() -> { // Your code here latch.countDown(); }).start(); new Thread(() -> { // Your code here latch.countDown(); }).start(); latch.await(); } |
Пример:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void testMultiThreadedCode() throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Integer> future1 = executorService.submit(() -> { // Your code here return 1; }); Future<Integer> future2 = executorService.submit(() -> { // Your code here return 2; }); assertEquals(1, future1.get().intValue()); assertEquals(2, future2.get().intValue()); } |
Важно убедиться, что многопоточный код корректно работает и не происходит гонка данных или блокировки. Также необходимо убедиться, что код не содержит ошибок и работает корректно при различных условиях.