I have 2 questions:
1. why run() is not called when I run the program
2. if run() is called, will it change the value of randomScore?
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);
}
}
}
Most importantly, you need to change
to
since
(int) Math.random()always will equal 0.Another important thing to notice is that main thread continues and prints the value of
randomScorewithout waiting for the other thread to modify the value. Try adding aThread.sleep(100);after thestart, orstudent.join()to wait for the student thread to finish.You should also be aware of the fact that the Java memory model allows for threads to cache their values for variables. It may be that the main thread has cached it’s own value.
Try making the randomScore volatile: