Java multithreading accumulates and repeats for the first time

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Start implements Runnable {
    protected int count = 0;

    @Override
    public void run() {
        while (count < 100) {
            countPP;
            System.out.println(Thread.currentThread().getName() + " count:" + count);
        }
    }

    public static void main(String[] args) {
        Runnable runnable = new Start();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 2; iPP) {
            executorService.execute(runnable);
        }
        executorService.shutdown();
    }
}

the first accumulation will be repeated, if the lock is the sequential output is basically a thread of work, is not the first time my code read and write problems.

Aug.03,2021

    There is a problem with the implementation of
  1. multithreading. Why is the same Runnable object submitted three times? if you want multiple threads to modify a value concurrently, you should declare count as a static global variable and create multiple Runnable tasks to run concurrently.
  2. countPP is not an atomic operation, and there are bound to be problems. It is recommended to use the AtomicInteger type to control concurrency

Lock you see that it is basically just one thread working because there are too few times. If you raise it to 10000 or more, you can see the difference

.
while (count < 10000) {
    synchronized (this) {
        countPP;
        System.out.println(Thread.currentThread().getName() + " count:" + count);
    }
}

countPP itself is not thread safe, lock (as above) or use AtomicInteger .

add that
using volatile decorations does not solve the problem that countPP is not thread-safe. For thread safety of self-increment operations, please see this article PP operations and related issues


count is not thread safe, refer to the atomic operation class, or the usage of synchronized


countPP; this operation first reads the count value in the thread's local memory, then performs the PP operation, and finally Synchronize to the main memory. So the following problems arise:

1:count = 0;
2:count = 0;
1:countPP; count = 1;
2:countPP; count = 1;

solution

1AtomicIntegerint;
2
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b41e22-2bb16.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b41e22-2bb16.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?