原创文章,未经作者允许,禁止转载!!!!!!!
如何用java是一段代码运行一段时间之后自动停止运行?
就拿打印随机函数的代码来做例子吧,让程序随机打印1-10的数字,打印十秒钟后停止打印:
public class RandomPrint{
public static void randomprint(int seconds){
long start = System.currentTimeMillis();
long end = start + (seconds)*1000; // seconds * 1000 ms/sec
for (int i = 0;i<100000000;){
System.out.println((int)(1+Math.random()*10));
i++;
if(System.currentTimeMillis() >= end) break;
}
}
public static void main(String[] args) {
randomprint(10);//Stop my program at 3 seconds
}
}
(int)(1+Math.random()*10)指的是随机取1-10中的一个数字,返回的是int类型
另外还有一种方法,但是此方法会一直打印,不会停止,不知道是哪里错了
public class RandomPrint {
public static void randomprint(){
for (int i=0;i<100000000;i++){
System.out.println((int)(1+Math.random()*10));
}
}
public static void main(String[] args){
long begain = System.currentTimeMillis();
long CheckTime = System.currentTimeMillis();
while(true){
RandomPrint.randomprint(); //this is the program need to work
CheckTime = System.currentTimeMillis();
if((CheckTime-begain)>=(10*1000)){
System.out.println("10 seconds stop!");
break;
}
}
}
}