When you use java multithreading, you get incredible results, and you can't figure out how to get it for a long time.

1. Want to understand the relationship between different types of threads (this program does not consider thread safety), want to simulate how the computer executes multithreading, but get an inexplicable result. After thinking about it for a long time, I still haven"t solved it, hoping to get help.

2, the code is as follows

   public class StudentDemo {
        public static void main(String[] args) {
            Student s = new Student();

            SetThread st = new SetThread(s);
            GetThread gt = new GetThread(s);
        
            Thread t1 = new Thread(st, "SetTread");
            Thread t2 = new Thread(gt,"GetTread");
        
            t2.start();
            t1.start();
        }
    }

    public class Student {
        public String  name;
        public int age;
    }

    public class SetThread implements Runnable{
        private Student s;

        public SetThread(Student s) {
            this.s = s;
        }

        @Override
        public void run() {
           s.name = "jzian";
           s.age = 27;
        }
    }

    public class GetThread implements Runnable {
        private Student s;

        public GetThread(Student s) {
           this.s = s;
        }

        @Override
        public void run() {
            System.out.println( s.name + "-----" + s.age);
        }
    }

3. The result is:
null-27
how did you get such a result?

Mar.07,2021

this should have nothing to do with instruction reordering. The compiler rearranges the order of instructions in some cases, but it must be for a certain reason. I don't see why the instructions should be reordered in this code.

I think the reason is probably visibility. Neither variable is volatile, so there is no guarantee that a value assigned in one thread will be visible in another thread. You can try adding volatile, and see if this happens again. If it does not appear, it has nothing to do with instruction rearrangement

The execution order of

child threads S1 and S2 is uncertain, so the result you are talking about is one of the possible results


java multithread scheduling is preemptive by default. Thread T1 is in the middle of execution (assigning a value to age), when T2 grabs the right to execute and prints out that only age,name is the default value of type String.


the problem lies here
t2.start ();
t1.start ();

Thread executes the get method first. The set method you haven't set yet defaults to null and 0. Why is there a value sometimes? because of the randomness of the thread, sometimes T1 executes first and T2 executes later, you get 27 br Zjan
first
t1.start ();
t2.start ();.
if you want to ensure that all you get is 27 br Zjan, but also to ensure thread synchronization, the above keywords volatie and synchronize can solve
mobile phone codewords, excuse me

Menu