Why does the method start not called?

I have 2 questions: 1. Why run () is not called when the program starts 2. If run () is called, will randomScore change the value?

    import java.*;


public class StudentThread extends Thread {
    int ID;  
    public static volatile int randomScore;   //will it change the value of randomScore defined here?
      StudentThread(int i) {
          ID = i;
      }

      public void run() {
          randomScore = (int)( Math.random()*1000);
      }

public static void main(String args[]) throws Exception {
    for (int i = 1;i< 10 ;i++) 
    {
            StudentThread student = new StudentThread(5);
            student.start(); 
            System.out.println(randomScore);
    }             
}  
 }
+3
source share
5 answers

Most importantly, you need to change

randomScore = (int) Math.random() * 1000;

to

randomScore = (int) (Math.random() * 1000);
                    ^                    ^

since it (int) Math.random()will always be 0.


Another important thing to note is that the main thread continues and prints the value randomScore, without waiting for another thread to change the value. Try adding Thread.sleep(100);after startor student.join()to wait until the student stream ends.


You should also be aware that the Java memory model allows threads to cache their values ​​for variables. Perhaps the main thread has cached its own value.

randomScore volatile:

public static volatile int randomScore;
+5
  • , . student.join() student.start()
  • run(), randomScore, , @aioobe .
+1

, , . , .

, ​​ , CountdownLatch ( 1 , latch.await()) , , Thread.join(), .

+1

, Math.random int 1000.

  randomScore = (int) (Math.random()*1000);

, :

  • (inital state)

    • Math.random , 0 1
    • double int, 0
    • 0 1000, 0.

, .

TL; DR:

  • run()

  • , , . , 0 run.

+1

Yes, the method is being called run. But it may be too fast. You can join threadwith the main one threadand wait a while.

+1
source

Source: https://habr.com/ru/post/1791803/


All Articles