java如何编写线程睡眠工具类包括随机睡眠时长

2025-10-23 00:28:54

1、好,我们首先创建一个Sleep类作为线程睡眠的工具类

java如何编写线程睡眠工具类包括随机睡眠时长

2、好,接下去我们写入第一个静态方法,就是普通的线程睡眠,将异常catch处理掉

/**

* 睡眠n毫秒

* @param time

*/

public static void threadSleep(int time){

try {

Thread.sleep(time);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

java如何编写线程睡眠工具类包括随机睡眠时长

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

java如何编写线程睡眠工具类包括随机睡眠时长

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();

}

}

java如何编写线程睡眠工具类包括随机睡眠时长

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

java如何编写线程睡眠工具类包括随机睡眠时长

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();

}

}

}

java如何编写线程睡眠工具类包括随机睡眠时长

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢