Adding Synchronize to the run () method by multithreading does not guarantee the thread Synchronize.

< H2 > problem description < / H2 >
  1. create a thread instance using the inherited Thread method
  2. when overriding the run () method, modify the run () method with the synchronized keyword
  3. the result is that the threads are not carried out by Synchronize, and there is a problem with the calculation result
< H2 > Code snippet < / H2 >
public class MyThreadDemo9 extends Thread{
    private static int count = 0;
    public String status;
    public MyThreadDemo9(String status){
        this.status = status;
    }
    @Override
    public synchronized void run() {
        for(int i = 0; i < 100; iPP) {
            countPP;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 100; iPP) {
            MyThreadDemo9 m8 = new MyThreadDemo9("Thread status - " + i);
            m8.start();
        }
        Thread.sleep(3000);
        System.out.println(MyThreadDemo9.count);
    }
}

what is the reason for this? can"t you modify the run () method with the synchronized keyword

Nov.15,2021

tell me loudly: what is the target of synchronized ?!


what you lock here is each thread object itself, but there is no concurrency control. Here you can add thread safety with AtomicInteger


you are locking the object, but the shared variables here belong to the class. It doesn't belong to the object itself, you should lock the class.

Menu