A little test about thread safety

 

Start 100 threads + 1, loop 100 times to check the results, normally it should be 100, right?

public static int t = 0;
    public static void main(String[] args) throws InterruptedException {
        for (int i=0;i<100;i++){
            for (int j=0;j<100;j++){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        add();
                    }
                }).start();
            }
            //打印t的值
            System.out.println(t);
            t = 0;
        }
    }

    public static void add(){
        t = t + 1;
        System.out.println("t after "+t);
    }

It can be seen that 100 threads operate on member variable a. The thread is not safe. You can open the t after comment and see it. The results are as follows

t after 95
t after 96
t after 97
t after 98
t after 99
99 

So how to ensure thread safety?

1. Add synchronized, the smaller the range, the better, because it is blocking, here you can add this keyword to the add method

2. Lock, you can also lock a = a + 1

3. Use the JUC class, such as AtomicIntege

Here we use atomicInteger as an example. CAS is used to ensure thread safety. If you don’t understand, you can check it out.

public static AtomicInteger t = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        for (int i=0;i<100;i++){
            for (int j=0;j<100;j++){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        add();
                    }
                }).start();
            }
            //打印t的值
            System.out.println(t);
            Thread.sleep(2000);//每隔2s置0重计数
            t = new AtomicInteger(0);
        }
    }

    public static void add(){
        int x = t.incrementAndGet();
        System.out.println("t after "+x);
    }

The result is as follows

t after 95
t after 96
t after 97
t after 98
98
t after 99
t after 100

You will find that the value of printing t is 98, but the subsequent runs have been completed for 2 times, and the final result is the value we want to print, so we can wait 2s before printing t to wait for the thread to complete, and the printing of t Will be right

 

 

Guess you like

Origin blog.csdn.net/Goligory/article/details/106176965