服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 浅析Java随机数与定时器

浅析Java随机数与定时器

2021-04-06 12:52彬菌 Java教程

本篇文章给大家分析了Java随机数与定时器的实现原理以及代码分享,有需要的读者参考下吧。

产生90-100的重复的随机数

?
1
2
3
4
5
6
7
8
9
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不重复的随机数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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的重复的随机数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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(); //调用定时任务
 }
}

本文转载于:https://www.idaobin.com/archives/301.html

延伸 · 阅读

精彩推荐