Question

I'm generating a random number every 10 second and Storing and Updating the number every 10...

I'm generating a random number every 10 second and Storing and Updating the number every 10 second when I generate new number in UpdateInt method. However, In my main method when I called UpdateInt method it generate every 10 second new number but it doesn't update and store in the arraylist.

***I want the Runnable to be in the arraylist method. Not in main method. my goal is to send the arraylist that has the update number***

import java.util.ArrayList;

import java.util.Random;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class EverySecond {

public static int genrand() {

Random number = new Random();

//generate random number

int rand = number.nextInt(1000);

//return generated random number

return rand;

}

public static ArrayList<Integer> UpdateInt(){

ArrayList<Integer> Update = new ArrayList<Integer>();

Runnable helloRunnable = new Runnable() {

public void run() {

int CurrentNum = genrand(); //create a random number

System.out.println("generate number ==== " + CurrentNum);

Update.add(CurrentNum);//update it in array list

}

};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

//schedule thread for evry 10 seconds

executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);

return Update;

}

public static void main(String[] args) throws Exception {

ArrayList<Integer> getUpdate=UpdateInt();

for(int x=0;x<getUpdate.size();x++) {

System.out.println("Current Num = " + getUpdate.get(x));

}

}

}

Current Output:

generate number ==== 367

generate number ==== 944

It should be :

generate number ==== 367

Current Num = 367

generate number ==== 47

Current Num = 47

NOTE: ***I want the Runnable to be in the arraylist method. Not in main method. my goal is to send the arraylist that has the update number***

I should get the same number in main method when Ioop that I generated in UpdateInt method. Note: I want the Runnable() to be in arraylist method and return the arraylist that has the update number. I would apperciate any help.

Homework Answers

Answer #1

Hi,

Please find updated code below.

For this since we return a value we need a callable wrapped around in runnable.

runnable is required to run at every 10 seconds.

Callable is required to return updated array.

As demonstrated in program below.

Main.java :

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Main
{
public static void main(String[] args) throws Exception
{
  
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  
//schedule thread for evry 10 seconds
  
//executor.schedule(new sampleCallableExample(), 1, TimeUnit.MILLISECONDS);
executor.scheduleAtFixedRate(new sampleCallableExample(), 0, 10, TimeUnit.SECONDS);
System.out.println("array size:"+globals.Update.size());
for(int x=0;x<globals.Update.size();x++)
{
  
System.out.println("Current Num = " + globals.Update.get(x));
  
}
  
}
}

Kindly declare Update array as global variable: inside new class globals as shown below:

import java.util.ArrayList;
public class globals
{
public static ArrayList<Integer> Update = new ArrayList<Integer>();
  
}

sampleCallableExample.java :

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.Random;
class sampleCallableExample implements Runnable
{
public static int genrand()
{
Random number = new Random();
//generate random number
int rand = number.nextInt(1000);
//return generated random number
return rand;
}
public Object call() throws Exception
{
//ArrayList<Integer> Update = new ArrayList<Integer>();
int CurrentNum = genrand();
System.out.println("generate number ==== " + CurrentNum);
globals.Update.clear();
globals.Update.add(CurrentNum);
System.out.println("Number added");
return globals.Update;
}

// As seen run wraps call object
public void run()
{
try
{
Object o = call();
//System.out.println("Returned " + o);
}
catch (Exception e)
{
e.printStackTrace();
}
}

public sampleCallableExample()
{
try
{
run();
  
  
}
catch(Exception e)
{
}
  
}
  
}   

output attached: You can see current num and generated number updated.

Thanks,

kindly upvote.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Complete the following program. This program should do the following: 1. Creates a random integer in...
Complete the following program. This program should do the following: 1. Creates a random integer in the range 10 to 15 for variable: allThreads, to create a number of threads. 2. Creates a random integer for the size of an ArrayList: size. 3. Each thread obtains a smallest number of a segment of the array. To give qual sized segment to each thread we make the size of the array divisible by the number of threads: while(size%allThreads != 0)size++ 4....
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
/* This program should check if the given integer number is prime. Reminder, an integer number...
/* This program should check if the given integer number is prime. Reminder, an integer number greater than 1 is prime if it divisible only by itself and by 1. In other words a prime number divided by any other natural number (besides 1 and itself) will have a non-zero remainder. Your task: Write a method called checkPrime(n) that will take an integer greater than 1 as an input, and return true if that integer is prime; otherwise, it should...
I need to get the Min and Max value of an array when a user inputs...
I need to get the Min and Max value of an array when a user inputs values into the array. problem is, my Max value is right but my min value is ALWAYS 0. how do i fix this? any help please!!! _________________________________________________________________________________________________ import java.util.Scanner; public class ArrayMenu{ static int count; static Scanner kb = new Scanner(System.in);             public static void main(){ int item=0; int[] numArray=new int[100]; count=0;       while (item !=8){ menu(); item = kb.nextInt();...
Create a class named Purchase. Each Purchase contains an invoice number, amount of sale, and amount...
Create a class named Purchase. Each Purchase contains an invoice number, amount of sale, and amount of sales tax. Include set methods for the invoice number and sale amount. Within the set() method for the sale amount, calculate the sales tax as 5% of the sale amount. Also include a display method that displays a purchase’s details. Provided code: import java.util.*; public class CreatePurchase { public static void main(String[] args) { Scanner input = new Scanner(System.in); Purchase purch = new...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
Hi, I'm writing a Java program that prints a grid with circles and squares that have...
Hi, I'm writing a Java program that prints a grid with circles and squares that have letters in them and it is also supposed to print the toString() function to the console window each time the application runs. This toString() function is supposed to show the tile's shape, letter, and color component (or components). Could someone please review and debug my code to help me figure out why my toString() function is not working? import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton;...
Question: I am using three different ways to execute this program. I am a bit confused...
Question: I am using three different ways to execute this program. I am a bit confused on the time complexity for each one. Can someone explain the time complexity for each function in relation to the nanoseconds. import java.util.HashMap; import java.util.Map; public class twosums {       public static void main(String args[]) {               int[] numbers = new int[] {2,3,9,4,8};;        int target = 10;               long nano_begin1 = System.nanoTime();        int[]...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.*; public class SJF { public static...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.*; public class SJF { public static void readFromFile() throws IOException { BufferedReader bufReader = new BufferedReader(new FileReader("processes.txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.readLine(); while (line != null) { listOfLines.add(line); line = bufReader.readLine(); } bufReader.close(); System.out.println("Content of ArrayLiList:"); // split by new line int num = 0; for (String line1 : listOfLines) { String line2[] = line1.split(","); // int burstTime = Integer.parseInt(line2[3].trim()); // String retrival = listOfLines.get(0); System.out.println("...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT