线程抛异常的问题
先看代码:
public class ThreadSleep implements Runnable {
Random rs = new Random();
int i = rs.nextInt() % 9 + 1;
public void run() {
System.out.println("线程开始:");
try {
Thread.sleep(i * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休眠了" + i + "秒钟");
}
}
启动这个线程.60%会抛出如下异常:
线程开始:
Exception in thread "pool-1-thread-1" java.lang.IllegalArgumentException: timeout value is negative
at java.lang.Thread.sleep(Native Method)
at cai.zhi.huan.ThreadSleep.run(ThreadSleep.java:12)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
但还有40%会正常运行:
线程开始:
休眠了1秒钟
请问.正常吗.?
如果用循环同时启动10次.那么99.9%会抛出异常.如果正常..那线程还有什么用?....