有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java随机化线程睡眠

我在runnable的run方法中有以下代码:

@Override
public void run(){
    final Random r=new Random(1000);
    int acquired=0;
    try{
        while(acquired < 1){
            for(int i=0;i<sems.length;i++){
                    if(sems[i].tryAcquire()){
                            System.out.println("Acquired for " + i);
                            Thread.sleep(r.nextInt());
                            sems[i].increment();
                            sems[i].release();
                            acquired=1;
                            break;
                    }
            }
        }

    }
    catch(InterruptedException x){}

}

在执行过程中,我不断遇到以下异常:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: timeout value is negative
        at java.lang.Thread.sleep(Native Method)
        at com.bac.jp.fourteenth$1.run(fourteenth.java:24)
        at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-0" java.lang.IllegalArgumentException: timeout value is negative
        at java.lang.Thread.sleep(Native Method)
        at com.bac.jp.fourteenth$1.run(fourteenth.java:24)
        at java.lang.Thread.run(Unknown Source)

但是,如果我使用线程。睡眠(1000)程序运行正常。 为什么我不能使用java Random将暂停随机化


共 (3) 个答案

  1. # 1 楼答案

    user.nextInt(1000)//返回0-999之间的数字。。。这解决了负回报问题

  2. # 2 楼答案

    随机数生成器生成了一个负数,当您将一个负值作为参数传递给Thread.sleep()时,您会得到一个即时异常

  3. # 3 楼答案

    Thread.sleep(r.nextInt(1000));替换Thread.sleep(r.nextInt());

    如果你看一下documentation,你会看到以下内容:

    nextInt
    
    public int nextInt()
    Returns the next pseudorandom, uniformly distributed int value from this random number 
    generator's sequence. The general contract of nextInt is that one int value is 
    pseudorandomly generated and returned. All 232 possible int values are produced with 
    (approximately) equal probability.
    
    The method nextInt is implemented by class Random as if by:
    
     public int nextInt() {
       return next(32);
     }
    Returns:
    the next pseudorandom, uniformly distributed int value from this random number 
    generator's sequence
    

    您将希望使用nextInt(int n),如下所示

    nextInt
    
    public int nextInt(int n)
    Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the 
    specified value (exclusive), drawn from this random number generator's sequence. The 
    general contract of nextInt is that one int value in the specified range is pseudorandomly 
    generated and returned. All n possible int values are produced with (approximately) equal 
    probability.