本文介绍了关于随机y线程的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个问题:

我有一个A类,其中有一个静态属性Random.在另一个类B中,有一个线程使用A的随机数来确定B类实例应朝哪个方向旋转,从而在整个画布上产生随机运动.问题是 一段时间后(B的实例越多,发生的越早),B的所有实例开始旋转一个小圈.就像A.random的预想值已经结束,并且它向B的所有实例返回相同的值.

I've a class A, wich have an static attribute Random. In another class B, there is a thread that uses A's random to decide in which direction the instance of the B class should turn, generating a random movement throughout the canvas. The problem is that after a while (the more instances of B, the sooner it happens) all the instances of B begin to spin in little circles. It's like the aleatory values of A.random are over, and it returns the same value to all the instances of B.

解决此问题的一种非常简单的方法是为B的每个实例创建一个新的随机变量,但是我想知道为什么会这样.

A very simple way to fix this is to create a new random variable to each instance of B, but I'd like to know why is this happening.

希望得到答案,谢谢.

MigueloH

推荐答案

解决方案是使用Random类的 same 实例生成所有随机数.除了在类的每个实例中创建新的Random对象之外,您还可以创建一个静态的应用程序范围的类,该类返回将由所有类使用的同一Random对象:

The solution is to use the same instance of the Random class to generateall random numbers. Instead of creating a new Random object in each instance of your class, you could perhaps create a static application-wide class that returns the same Random object to be used by all classes:

  public static class ApplicationService
  {

    private static Random _random = new Random();

    public static Random Random {
      get {
        return _random;
      }
    }
  }

public class A
{
void SomeMethodA()
{
 Random random = ApplicationService.Random; //use this one
}
}

public class B
{
void SomeMethodB()
{
 Random random = ApplicationService.Random; //use this one
}
}


请记住将有用的帖子标记为答案和/或有用.


Please remember to mark helpful posts as answer and/or helpful.


这篇关于关于随机y线程的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:46