Java: From single-threaded counter to multi-threaded data synchronization synchronized and atomic class Atomic

use single thread

The value of the counter is modified by a single thread, and there is no problem. The result of each operation is 10000, but the program takes a long time

package com.example;

/**
 * 计数器
 */
class Counter {
    
    
    private static long count;

    public static long getCount() {
    
    
        return count;
    }

    public static void incrementCount() {
    
    
        count++;
    }
}


public class Demo {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        long count = Counter.getCount();
        System.out.println(count);
        // 0

        for (int i = 0; i < 10000; i++) {
    
    
            try {
    
    
                Thread.sleep(1);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            Counter.incrementCount();
        }
        
        count = Counter.getCount();
        System.out.println(count);
        // 10000
    }
}

use multithreading

The value of the counter is modified by a single thread, and the running speed is improved, but the running result is inconsistent every time, and the result is not 10000

package com.example;

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

/**
 * 计数器
 */
class Counter {
    
    
    private static long count;

    public static long getCount() {
    
    
        return count;
    }

    public static void incrementCount() {
    
    
        count++;
    }
}


public class Demo {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        long count = Counter.getCount();
        System.out.println(count);
        // 0

        List<Thread> list = new ArrayList<>();

        // 启动10000个线程同时访问计数器
        for (int i = 0; i < 10000; i++) {
    
    
            Thread thread = new Thread(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    try {
    
    
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    Counter.incrementCount();
                }
            });
            list.add(thread);
        }

        for (Thread thread : list) {
    
    
            thread.start();
        }

        for (Thread thread : list) {
    
    
            thread.join();
        }

        count = Counter.getCount();
        System.out.println(count);
    }
}

Results of the

第一次:9910
第二次:9912
第三次:9910

Use multithreading + synchronized

After multi-thread locking, the final result is 10000

package com.example;

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

/**
 * 计数器
 */
class Counter {
    
    
    private static long count;

    public static long getCount() {
    
    
        return count;
    }

    public static synchronized void incrementCount() {
    
    
        count++;
    }
}


public class Demo {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        long count = Counter.getCount();
        System.out.println(count);
        // 0

        List<Thread> list = new ArrayList<>();

        // 启动10000个线程同时访问计数器
        for (int i = 0; i < 10000; i++) {
    
    
            Thread thread = new Thread(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    try {
    
    
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    Counter.incrementCount();
                }
            });
            list.add(thread);
        }

        for (Thread thread : list) {
    
    
            thread.start();
        }

        for (Thread thread : list) {
    
    
            thread.join();
        }

        count = Counter.getCount();
        System.out.println(count);
    }
}

Results of the

第一次:10000
第二次:10000
第三次:10000

Use multithreading + atomic class AtomicLong

The atomic class AtomicLong is used to implement the counter in multithreading, and the final result is 10000

The principle is CAS(Compare and Set):

  • First compare the original value and the expected value, and if they are equal, modify it to the new value;
  • If not equal, the modification fails

The pseudo code is as follows

bool compareAndSet(oldValue, expectValue, updateValue){
    
    
    if(oldValue == expectValue){
    
    
        oldValue = updateValue
        // update success
    } else{
    
    
        // update fail
    }
}
package com.example;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 计数器
 */
class Counter {
    
    
    private static AtomicLong count = new AtomicLong(0);

    public static long getCount() {
    
    
        return count.get();
    }

    public static void incrementCount() {
    
    
        count.incrementAndGet();
    }
}


public class Demo {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        long count = Counter.getCount();
        System.out.println(count);
        // 0

        List<Thread> list = new ArrayList<>();

        // 启动10000个线程同时访问计数器
        for (int i = 0; i < 10000; i++) {
    
    
            Thread thread = new Thread(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    try {
    
    
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    Counter.incrementCount();
                }
            });
            list.add(thread);
        }

        for (Thread thread : list) {
    
    
            thread.start();
        }

        for (Thread thread : list) {
    
    
            thread.join();
        }

        count = Counter.getCount();
        System.out.println(count);
    }
}

Results of the

第一次:10000
第二次:10000
第三次:10000

reference

  1. Using Atomic-Liao Xuefeng's official website
  2. CAS lock mechanism (no lock, spin lock, optimistic lock, lightweight lock)
  3. Atomic class in java

Guess you like

Origin blog.csdn.net/mouday/article/details/130923836