ok. I need to make three threads: one to get odd numbers, one to get evens, and one to add the odd and evens together. The output would be something like this (1,2,3,3,4,7...). I'm new to threads and still shaky on how they work but this is what I have so far:
class even extends Thread
{
public void even()
{
Thread ThreadEven = new Thread(this);
start();
}
public void run()
{
try
{
for(int i = 0; i < 10; i += 2)
{
System.out.println(i);
}
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Error: Thread Interrupted");
}
}
}
class odd extends Thread
{
public void odd()
{
Thread ThreadOdd = new Thread(this);
start();
}
public void run()
{
try
{
for(int i = 1;i < 10; i += 2)
System.out.println(i);
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Error: Thread Interrupted");
}
}
}
class ThreadEvenOdd
{
public static void main(String args [])
{
even e = new even();
odd o = new odd();
}
}
This prints out 0,2,4...and then 1,3,5. How to interleave? And is interleaving what I want and should I synchronize the threads as well? What I don't understand is how to get the values of the odd and even thread into a third to add the sum. Apologies beforehand if I didn't get the formatting correct for the code.