英文:
Generate number every 3 seconds and update current number
问题
以下是翻译好的内容:
我正在尝试每3秒生成一个数字并更新当前数字。我能够每3秒生成一个数字;然而,当前数字没有被更新。我感谢任何帮助。
public static void main(String[] args) {
Runnable helloRunnable = new Runnable() {
public void run() {
CurrentNum = task2();
System.out.println("Result ==== " + CurrentNum);
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);
System.out.println("CurrentNum ==== " + CurrentNum);
}
public static int task2() {
// create instance of Random class
Random rand = new Random();
// Generate random integers in range 0 to 999
int rand_int1 = rand.nextInt(1000);
return rand_int1;
}
输出:
Result ==== 631
Result ==== 789
Result ==== 958
Result ==== 379
英文:
I'm trying to generate a number every 3 seconds and update the current number. I'm able to generate number every 3 seconds; However, the current number isn't updated. I apperciate any help.
public static void main(String[] args) {
Runnable helloRunnable = new Runnable() {
public void run() {
CurrentNum=task2();
System.out.println("Result ==== "+CurrentNum);
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);
System.out.println("CurrentNum ==== "+CurrentNum);
}
public static int task2() {
// create instance of Random class
Random rand = new Random();
// Generate random integers in range 0 to 999
int rand_int1 = rand.nextInt(1000);
return rand_int1;
}
output:
CurrentNum ==== 0
Result ==== 631
Result ==== 789
Result ==== 958
I want the output to be:
Result ==== 631
CurrentNum ==== 631
Result ==== 789
CurrentNum==== 789
答案1
得分: 0
The print for CurrentNum will only get printed once because it will only run once. Since the runnable is running on an interval, that will get called every 3 seconds. If you want the print for CurrentNum to be printed, you move the System.out.println("CurrentNum ==== "+CurrentNum);
Line Inside the helloRunnable function.
System.out.println("CurrentNum ==== "+CurrentNum);
CurrentNum=task2();
System.out.println("Result ==== "+CurrentNum);
英文:
The print for CurrentNum will only get printed once because it will only run once. Since the runnable is running on an interval, that will get called every 3 seconds. If you want the print for CurrentNum to be printed, you move the System.out.println("CurrentNum ==== "+CurrentNum);
Line Inside the helloRunnable function.
System.out.println("CurrentNum ==== "+CurrentNum);
CurrentNum=task2();
System.out.println("Result ==== "+CurrentNum);
专注分享java语言的经验与见解,让所有开发者获益!
评论