Joh*_*ohn 3 java multithreading
我有两个问题:1.为什么运行程序时没有调用run()2.如果调用run(),它会改变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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
最重要的是,你需要改变
randomScore = (int) Math.random() * 1000;
Run Code Online (Sandbox Code Playgroud)
至
randomScore = (int) (Math.random() * 1000);
^ ^
Run Code Online (Sandbox Code Playgroud)
因为(int) Math.random()总是等于0.
另一个需要注意的重要事项是主线程继续并打印值randomScore而不等待其他线程修改该值.尝试添加Thread.sleep(100);后start,或student.join()等待学生线程完成.
您还应该意识到Java内存模型允许线程缓存其变量值.可能是主线程缓存了它自己的值.
尝试使randomScore变量:
public static volatile int randomScore;
Run Code Online (Sandbox Code Playgroud)