How to use threads to generate numbers
I am new to Java threads, and would like to use them to solve the following problem. Any help or references to similar problems is
appreciated.
The GenerateNumbers class is used by main to list integers (0,1,2,...) by:
Code:
GenerateNumbers g = new GenerateNumbers();
while( true )
System.out.println( g.getNumber() ) ;
I know that you can easily do this without threads, but I want to use concurrency (as a learning exercise, and as my method easily generalizes to pairs, triples, etc.). All thread details must be "hidden" in the GenerateNumbers class, ie main doesn't care if GenerateNumbers does or does not use threads.
Here's the outline to be completed.
Code:
public class GenerateNumbers
{
private int n;
public GenerateNumbers ()
{
n = 0;
// ?? set up thread and start generate ??
}
public int getNumber ()
{
// ?? resume generate ??
return n--;
}
private void generate ()
{
while ( true )
{
// ?? wait (continue when resumed) ??
n++;
}
}
}
Re: How to use threads to generate numbers
Can you explain how you plan to use threads? What will each thread do? How will it interact with the other threads?
How will execution pass from one thread to another?
Re: How to use threads to generate numbers
Adding on Norm's question, Yes without clear understanding of Threads and purpose it could be dangerous to use them. Threads are used to add parallelism in code e.g. animation where multiple things happening same time. In your case if you want to print numbers you can implemente runnable and put code of printing number inside run() method and when you create and start thread using java.lang.Thread that code will run in parallel with whatever there is left in main method or main thread.