In: Computer Science
Can someone give me a detailed explanation as to what
Random generator = new Random();
Thread.sleep(generator.nextInt(1001)); does in java?
Random generator = new Random();
Thread.sleep(generator.nextInt(1001));
1) Random generator = new Random();
This statement creates an instance of random class to generate a
random number .
Random generator can only be generated using the object of random
class.
The object created here is "generator".
2) Thread.sleep(generator.nextInt(1001));
Here, generator.nextInt(1001) produces a random integer between 0 and 1001.
Thread.sleep() - This function is used to pause the execution of the current thread.
Threads are used to run multiple processes at the same time.
Say for example we have a loop to print 0 to 10000. and a loop to print hello thousand times.
We can run these tasks parallel to each other using threads or we can pause one task for a certain time and execute the other thread.
Thread.sleep(time) - time is the parameter required to specify the amount of time the thread must be paused for.
In the above case, it will be a random milli-second between 0 to 1001 - generated by the random function above.
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)