The while loop in this question is thread safe: AtomicInteger thread safety. If I insert the randomSum method in the thread safe while loop, is the code still thread safe? Or should the randomSum method be synchronized?
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class Print implements Runnable {
static AtomicInteger atomicInteger = new AtomicInteger(0);
static Random random = new Random(1);
public static int randomSum() {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += random.nextInt();
}
return sum;
}
@Override
public void run() {
while (atomicInteger.getAndIncrement() < 100)
System.out.println(randomSum() + " " + Thread.currentThread());
}
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < 5; i++)
threads.add(new Thread(new Print()));
for (Thread thread : threads)
thread.start();
for (Thread thread : threads)
thread.join();
}
}