In: Computer Science
I'm trying to Generate number every 3 seconds and update the currenet number.I'm able to generate number every 3 seconds; However, the current number isn't update. 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 tobe:
Result ==== 631
CurrentNum ==== 631
Result ==== 789
CurrentNum==== 789
CODE:
import java.util.*;
import java.util.concurrent.*;
class Generate
{
static int CurrentNum;//we have declare this as static in order
change it in innerclass.
public static void main(String[] args)
{
Runnable helloRunnable = new Runnable()
{
public void run() {
CurrentNum=task2();
System.out.println("Result ==== "+CurrentNum);
}
};
//here the value is changed but not viewed because we cannot
concurrent main method.
while(true)
{
//here the executor executes only the runnable method not the main
method.
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;
}
}
CODE ATTACHMENTS:

OUTPUT:

Here in your code there is no error but the concurrent time is printed only once.
The value of concurrentnum is changing but not visualised as the scheduledexecutor only executes the runnable not the main.
When the run method and loop are synchronized then prints the required values as shown in the output.
However they both continuously execute infinitely and you can find the required output.
Please do comment for any queries.
PLease like it.
Thank You.