Я ожидал, что результат должен быть меньше 0 (не всегда, но иногда), потому что это не так. синхронизировано.
Но приведенный ниже тест не пройден.
Код: Выделить всё
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
class OptionTest {
static class Option {
private int quantity;
public Option(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public boolean subtract(int quantity){
if(quantity >= this.quantity){
return false;
}
// System.out.println("quantity = " + quantity);
this.quantity -= quantity;
return true;
}
}
@Test
void asyncSubtract() throws InterruptedException {
int numberOfThreads = 100; // Increased number of threads
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
List tasks = new ArrayList();
Option option = new Option(201);
for (int i = 0; i < numberOfThreads; i++) {
tasks.add(() -> option.subtract(50));
}
executorService.invokeAll(tasks);
executorService.shutdown();
assertThat(option.getQuantity()).isLessThan(1);
}
}
Код: Выделить всё
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
class OptionTest {
static class Option {
private int quantity;
public Option(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public boolean subtract(int quantity){
if(quantity >= this.quantity){
return false;
}
System.out.println("quantity = " + quantity);
this.quantity -= quantity;
return true;
}
}
@Test
void asyncSubtract() throws InterruptedException {
int numberOfThreads = 100; // Increased number of threads
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
List tasks = new ArrayList();
Option option = new Option(201);
for (int i = 0; i < numberOfThreads; i++) {
tasks.add(() -> option.subtract(50));
}
executorService.invokeAll(tasks);
executorService.shutdown();
assertThat(option.getQuantity()).isLessThan(1);
}
}
Может ли кто-нибудь объяснить результат этого теста?
Есть ли какая-то магия JVM?
Подробнее здесь: https://stackoverflow.com/questions/787 ... -synchroni