Recently I was preparing for the java interview and realized that I do not know why this code works correctly in multithreading environment. I created 100 threads and only one of them printed test, why it is happening? volatile here works like synchronized, but it should not.
import java.util.ArrayList;
import java.util.List;
public class PrintInOrder {
private volatile boolean first = true;
public static void main(String[] args) throws InterruptedException {
PrintInOrder printInOrder = new PrintInOrder();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 100; i++) {
threads.add(new Thread(printInOrder::first));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
}
public void first() {
while (!first) {
}
System.out.println("first");
first = false;
}
}