3
사이클에서 calculateValue의 최대 값을 얻으려고했는데 스레드로부터 안전하다고 생각했습니다. 그래서 AtomicInteger와 Math.max를 사용하기로 결정했는데, 그 작업이 원자 적으로 간주 될 수 있도록 솔루션을 찾을 수 없습니다.AtomicInteger and Math.max
AtomicInteger value = new AtomicInteger(0);
// Having some cycle here... {
Integer anotherCalculatedValue = ...;
value.set(Math.max(value.get(), anotherCalculatedValue));
}
return value.get()
문제점은 두 가지 작업을하므로 스레드 안전하지 않다는 것입니다. 이 문제를 어떻게 해결할 수 있습니까? 유일한 방법은 synchronized
을 사용하는 것입니다. 자바 (8)를 사용할 수있는 경우
이것은 내가 필요한 것입니다. 나는 실행중인 스레드의 최대 수를 알고 싶었 기 때문에 다음과 같이 run() 메서드를 시작할 때이 값을 줄였습니다. (끝에서 감소) : 'public void run() { int actNow = activeCount. incrementAndGet(); maxActive.getAndAccumulate (actNow, Math :: max);' – user1683793