Results 1 to 3 of 3
- 02-08-2012, 01:50 AM #1
Member
- Join Date
- Feb 2012
- Posts
- 1
- Rep Power
- 0
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:
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.Java Code:GenerateNumbers g = new GenerateNumbers(); while( true ) System.out.println( g.getNumber() ) ;
Here's the outline to be completed.
Java 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++; } } }Last edited by Lew; 02-08-2012 at 04:01 PM. Reason: simplify code
- 02-08-2012, 03:42 AM #2
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?
- 02-18-2012, 07:15 AM #3
Member
- Join Date
- Oct 2011
- Posts
- 33
- Rep Power
- 0
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.
Similar Threads
-
Random Numbers using threads
By subash22 in forum Threads and SynchronizationReplies: 1Last Post: 06-05-2011, 03:09 PM -
Generate weighted random numbers, nextGaussian ()
By graympa in forum New To JavaReplies: 2Last Post: 03-25-2011, 09:36 PM -
Generate prime numbers within fiboncacci series?
By Manish87 in forum New To JavaReplies: 9Last Post: 08-08-2010, 04:07 AM -
generate pseudo random numbers in java
By csr81 in forum Advanced JavaReplies: 3Last Post: 03-01-2010, 07:08 AM -
Generate numbers around a circle?
By pheonix in forum New To JavaReplies: 4Last Post: 06-05-2009, 05:08 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks