浅析Java随机数与定时器
更新时间:2018年02月24日 10:34:42 作者:彬菌
本篇文章给大家分析了Java随机数与定时器的实现原理以及代码分享,有需要的读者参考下吧。
产生90-100的重复的随机数:
public class RandomTest {
public static void main(String[] args){
/*
* Math.random()方法默认double类型,所以需要强制转换为int
*/
int x=(int)(Math.random()*(100-90+1)+90); //(max-min+1)+min=min-max
System.out.println(x);
}
}
产生90-100不重复的随机数:
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class RandomTest {
public static void main(String args[]){
int max=100; //最大值
int min=90; //最小值
int count=max-min; //随机数个数
Random random = new Random();
Set<Integer> set=new HashSet<>(); //hashset容器中只能存储不重复的对象
while(set.size()<count){ //hashset储存的元素数目
int x = random.nextInt(max-min+1)+min; //产生随机数
set.add(x); //把随机数添加到hashset容器中
}
for(int i:set){ //foreach遍历容器元素
System.out.println(i);
}
}
}
每一秒产生90-100的重复的随机数:
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class RandomTest {
void timer(){
Timer timer = new Timer(); //创建定时对象
timer.schedule(new TimerTask() {
public void run() { //TimerTask实现 Runnable接口的run方法
Random random = new Random();
int x = random.nextInt(100-90+1)+90; //(max-min+1)+min=min至max
// int x=random.nextInt(100)%(100-90+1) + 90; //同样的效果
System.out.println(x);
}
},0,1000); //0表示无延迟,1000ms=1s
}
public static void main(String[] args){
RandomTest ran=new RandomTest();
ran.timer(); //调用定时任务
}
}
相关文章
SpringCloud 中防止绕过网关请求直接访问后端服务的解决方法
这篇文章主要介绍了SpringCloud中如何防止绕过网关请求直接访问后端服务,本文给大家分享三种解决方案,需要的朋友可以参考下2023-06-06
Spring中的ApplicationContext与BeanFactory详解
这篇文章主要介绍了Spring中的ApplicationContext与BeanFactory详解,Spring的IoC容器就是一个实现了BeanFactory接口的可实例化类,事实上, Spring提供了两种不同的容器,一种是最基本的BeanFactory,另一种是扩展的ApplicationContext,需要的朋友可以参考下2024-01-01


最新评论