java如何编写线程睡眠工具类包括随机睡眠时长
1、好,我们首先创建一个Sleep类作为线程睡眠的工具类

2、好,接下去我们写入第一个静态方法,就是普通的线程睡眠,将异常catch处理掉
/**
* 睡眠n毫秒
* @param time
*/
public static void threadSleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

3、现在再调用线程睡眠方法就相当的简洁了,注意参数是毫秒值哦

4、接下去我们编写第二个静态方法,这个方法是用在模拟操作上常用的随机睡眠,在给定的间隔时间内随机产生睡眠时长
/**
* 睡眠n-m秒
* @param time 1-6
*/
public static void threadSleep(String time){
//1-6
String[] split = time.split("-");
int first = Integer.parseInt(split[0]);
int second = Integer.parseInt(split[1]);
try {
Thread.sleep((first+(int)(Math.random()*(second-first)))*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

5、调用我们的随机睡眠方法,就可以根据传入的参数进行随机睡眠了,不过random方法其实是伪随机哦

6、最后给大家贴下这个睡眠工具类的完整代码
public class Sleep {
/**
* 睡眠n毫秒
* @param time
*/
public static void threadSleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 睡眠n-m秒
* @param time 1-6
*/
public static void threadSleep(String time){
//1-6
String[] split = time.split("-");
int first = Integer.parseInt(split[0]);
int second = Integer.parseInt(split[1]);
try {
Thread.sleep((first+(int)(Math.random()*(second-first)))*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
