The created thread executes the Start method multiple times to output the result error

class MyThread implements Runnable{
    private int num = 5;

    public void run(){
        while(num>0) {
            System.out.println(Thread.currentThread().getName()+"--->"+this.num);
             num--;
        }
    }
}
public class test{
    public static void main(String[] args) {
        MyThread mt1 = new MyThread();
        new Thread(mt1,"Number 1").start();
        new Thread(mt1,"Number 2").start();
    }
}

first of all, the code is easy to understand, but when I compile and run, I am curious about the results, as shown in the figure. but why output 5 twice? . This is different from the answer I read in the book.

new Thread(mt1,"Number 3").start();

just learned java, has doubts about this. Isn"t num a shared global variable for these threads? Second, shouldn"t locking mechanisms be provided between these threads? (I inferred from the output of 1234) how can several threads access the same num at the same time?

I hope you guys can help me with this vegetable chicken, thank you.

Mar.25,2021

1. There is no automatic provision of locks between threads, so you need to use the keywords Sychronized, ReentrantLock class, and so on provided in java to implement thread Synchronize.
2. Calling the start method will only put the thread into the executable state, and then CPU will randomly schedule the thread in the executable state to execute.
3. Because it is multithreaded, it may occur that thread 1 prints the result first, and before thread 1 subtracts, the num remains unchanged, and thread 2, which is running at the same time, prints the same result.


1. Num is not a shared global variable. You probably understand it as a singleton mode, but to introduce the concept of cache here, you can directly cache 5 after each thread reads num for the first time, and then calculate it, and the system randomly adjusts the thread. In addition, self-increment and self-subtraction are not atomic.
2. Lock mechanism should be set by yourself. Volatile
3 on synchronized, solution

class MyThread implements Runnable{
    private int num = 5;
     // private volatile int num = 5;
    synchronized public void run(){
        while(num>0) {
            System.out.println(Thread.currentThread().getName()+"--->"+this.num);
            num--;
        }
        num=7;//
    }
}

4, related suggestions:

AIDEAEclipse 
BJava
Menu