Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么不调用run方法?_Java_Multithreading - Fatal编程技术网

Java 为什么不调用run方法?

Java 为什么不调用run方法?,java,multithreading,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? Stud

我有两个问题: 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);
    }             
}  
 }
importjava.*;
公共类StudentThread扩展线程{
int-ID;
public static volatile int randomScore;//是否会更改此处定义的randomScore的值?
学生线程(int i){
ID=i;
}
公开募捐{
randomScore=(int)(Math.random()*1000);
}
公共静态void main(字符串args[])引发异常{
对于(int i=1;i<10;i++)
{
StudentThread student=新的StudentThread(5);
student.start();
系统输出打印项次(随机分数);
}             
}  
}

最重要的是,您需要更改

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

因为
(int)Math.random()
始终等于0


另一个需要注意的重要事项是,主线程继续并打印
randomScore
的值,而不等待其他线程修改该值。尝试添加
线程。sleep(100)
开始之后,或
student.join()
等待学生线程完成


您还应该知道,Java内存模型允许线程缓存变量的值。可能是主线程缓存了自己的值

尝试使随机分数不稳定:

public static volatile int randomScore;
  • 您的run方法已被调用,但您没有等待它完成。在
    student.start()之后添加
    student.join()
  • 如果调用了
    run()
    方法,那么它将更改
    randomScore
    变量的值,但是您应该按照@aioobe的建议使这些更改可见

  • 它将更改该值,但您可能会在执行代码设置该值之前读取该值。毕竟,它是在另一个线程中执行的


    如果要保证在读取之前设置变量,可以使用(创建一个1的锁存并在设置变量后倒计时,在另一个线程中使用
    latch.await()
    ),或者使用
    thread.join()
    等待线程完成执行。

    代码中的真正问题是在将Math.random乘以1000之前将其强制转换为int

      randomScore = (int) (Math.random()*1000);
    
    当代码执行时,会发生以下情况

  • 将随机分数设置为零(初始状态)

  • 当您想要更改随机分数时

  • Math.random创建一个等于或大于0且小于1的双精度值
  • 您将双精度转换为始终为0的整数
  • 你将0乘以1000,得到的随机分数为0
  • 其余的答案给出了代码不是线程安全的原因

    TL;博士:

  • 在程序中调用run()方法

  • 不,不会,因为随机评分算法中有缺陷。实际上,每次执行run方法时,random score总是设置为0


  • 是的,正在调用
    run
    方法。但这可能太快了。您可以使用main
    thread
    加入
    线程
    ,然后等待一段时间。

    我只需再添加一个问题。你能帮助我吗?
      randomScore = (int) (Math.random()*1000);