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.
you need a way of “passing” the numbers from your producer threads (even & odd) to your “consumer” thread.
‘Simplest’ but not best way is a mutable array, with one entry — and you’ll have to synchronize/ lock on something (the array?) to avoid concurrent threads corrupting it.
Perhaps the easier & better way, might be to use a ‘double-ended queue’ such as ArrayDeque. This lets values be put in at one end, and removed from the other. Again, access to it needs to be synchronized.
Create the queues external to all threads, then pass them in/ or make them visible.