随机化线程睡眠

时间:2013-04-07 02:28:40

标签: java thread-safety

我在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)

但是,如果我使用Thread.sleep(1000),程序运行正常。 为什么我无法使用java Random随机化暂停?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

如果查看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. 
相关问题