繁体   English   中英

为什么不调用run方法?

[英]why run method is not called?

我有两个问题: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);
    }             
}  
 }

最重要的是,你需要改变

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

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

因为(int) Math.random()总是等于0。


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


您还应该意识到Java内存模型允许线程缓存其变量值。 可能是主线程缓存了它自己的值。

尝试使randomScore变量:

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

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

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

代码中的真正问题是,在将数字乘以1000之前,将Math.random转换为int。

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

当您的代码执行时会发生以下情况

  1. 您将随机分数设置为零(初始状态)

  2. 当您想要更改随机分数时

    1. Math.random创建一个等于或大于0且小于1的double值
    2. 您将double转换为始终为0的int
    3. 您将0乘以1000可得到随机分数0。

其余的答案为您提供了代码不是线程安全的原因。

TL; DR:

  1. 在程序中调用run()方法

  2. 不,它不会因为随机评分算法中存在错误。 实际上,每次执行run方法时,随机分数始终设置为0。

是的,正在调用run方法。 但它可能太快了。 您可以加入thread与主thread和等待一段时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM