Thread safety issues for code

import java.util.ArrayList;
import java.util.List;

public class Main {

    // ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    int i;

    public void increment() {
        iPP;
    }
    public static void main(String[] args) {

        Main main = new Main();
        
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                
                for (int i = 0; i < 10000; iPP) {
                    main.increment();
                    System.out.println(main.i);
                }
            }
        };
        List<Thread> threads = new ArrayList<>(10);
        for (int i = 0; i < 3; iPP) {
            Thread thread = new Thread(runnable);
            threads.add(thread);
            thread.start();
        }  
        boolean flag = false;
        while (!flag) {
            flag = true;
            for (Thread thread : threads) {
                if (thread.isAlive()) {
                    flag = false;
                }
            }

        }
        System.out.println(main.i);

    }
}

for System.out.println (main.i) in this for loop;
, after adding this sentence, the result of each output is 30000, which is why



public void println(int x) {
        synchronized (this) {
            print(x);
            newLine();
        }
}


synchronizedsynchronized

300
2999915

is not thread safety is certain. Just try it with 30300 threads. It gives you the illusion that it is safe. System.out.println is a time-consuming Synchronize method that largely masks the visibility and atomicity of iPP . Use AtomicInteger or synchronized Bar

Menu