0

我在可运行的运行方法中有以下代码:

@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)

但是,如果我使用 Thread.sleep(1000) 程序运行良好。为什么我不能使用 java Random 随机化暂停?

4

3 回答 3

2

使用r.nextInt(1000)// 返回一个 0-999 之间的数字...这解决了负返回问题

于 2013-04-07T02:37:04.427 回答
1

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

于 2013-04-07T02:34:15.630 回答
1

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

如果您查看文档,您将看到以下内容:

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. 
于 2013-04-07T02:41:02.490 回答