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将暂停随机化
# 1 楼答案
use
r.nextInt(1000)
//返回0-999之间的数字。。。这解决了负回报问题# 2 楼答案
随机数生成器生成了一个负数,当您将一个负值作为参数传递给
Thread.sleep()
时,您会得到一个即时异常# 3 楼答案
用
Thread.sleep(r.nextInt(1000));
替换Thread.sleep(r.nextInt());
如果你看一下documentation,你会看到以下内容:
您将希望使用
nextInt(int n)
,如下所示