This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Odd-Even Number print program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Odd-Even Number print program" Watch "Odd-Even Number print program" New topic
Author

Odd-Even Number print program

Purvesh Vora
Ranch Hand

Joined: Dec 10, 2003
Posts: 47
Hi All,

I don't know threads much....
During an interview I was asked to write a program so that THread1 always prints ODD number and Thread2 always prints EVEN number.
Can anybody please help me with the program.

Thanks,
Purvesh
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Make a runnable that increments by 2, start thread 1 at 1 and start thread 2 at 2?

Now if they really meant to make two threads that access a shared resource in turn, that would be more work. Do you think the runnable says this:

System.out.println( sharedResource.getNextInt() );

and we are supposed to get T1 and T2 to alternate?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Purvesh Vora
Ranch Hand

Joined: Dec 10, 2003
Posts: 47
Thanks for the reply Stan.

As u suggested I tried the foll. prog.

public class Test {

public static void main(String[] args) {
OddEven o1 = new OddEven("Odd Number Thread" , 1);
OddEven o2 = new OddEven("Even Number Thread" , 2);
o1.start();
o2.start();
}
}

====
public class OddEven extends Thread {
/**
* @param string
*/

private int number;

public OddEven(String name, int p_number){
super(name);
this.number = p_number;
}

public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName()+ this.number );
this.number +=2;
}
}
}

====
The above program first of all prints all odd numbers and then even number.
But What if I want to print the odd number followed by even number and then odd number then....

Need to use notifyall, wait and Synchronize...

Pls help.

Thanks & Regards,
Purvesh
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Yes, you could pass your two threads a common object and they could lock and unlock on that object. I'd have to stare at the ceiling a while to think of how to do it. Any ideas?
Purvesh Vora
Ranch Hand

Joined: Dec 10, 2003
Posts: 47
Stan,

I tried foll. after studying sun's thread tutorial.

some hardcoding in the code but it works.....

=====
public class Test {

public static void main(String[] args) {
System.out.println("Odd Even test");
NumHolder objNumHolder = new NumHolder();
Odd o1 = new Odd(objNumHolder, "Odd Number Thread");
Even e1 = new Even(objNumHolder, "Even Number Thread");
o1.start();
e1.start();
}
}

=============
public class NumHolder {
private int intCurrNum;
private boolean isEven = false;

public synchronized void printOddNumber(String tname) {
while (isEven == true){
try {
wait();
}catch (InterruptedException e) {
}
}
isEven = true;
System.out.println("Thread Name="+tname + "===Number="+intCurrNum);
intCurrNum += 1;
notifyAll();
}

public synchronized void printEvenNumber(String tname) {
while (isEven == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
isEven = false;
System.out.println("Thread Name="+tname + "===Number="+intCurrNum);
intCurrNum += 1;
notifyAll();
}
}
===================

public class Even extends Thread {
private NumHolder objNumHolder;

public Even(NumHolder p_objNumHolder, String name) {
super(name);
objNumHolder=p_objNumHolder;
}

public void run() {
for (int i = 0; i < 10; i++) {
objNumHolder.printEvenNumber(getName());
}
}
}

======================
public class Odd extends Thread {
private NumHolder objNumHolder;

public Odd(NumHolder p_objNumHolder,String name) {
super(name);
objNumHolder = p_objNumHolder;
}

public void run() {
for (int i = 0; i < 10; i++) {
objNumHolder.printOddNumber(getName());
}
}
}
======

Regards,
Purvesh
vrayudu kumar
Ranch Hand

Joined: Nov 20, 2003
Posts: 79
Hi Rupesh,

am new to threads.Can u explain this program..
Purvesh Vora
Ranch Hand

Joined: Dec 10, 2003
Posts: 47
Just a minor change in the program in the NumHolder class...
change
private int intCurrNum;
to
private int intCurrNum = 1;
============

Here is a shared object NumHolder which has method to print odd and even number and that methods are synchronized.

Odd and Even classes extend thread and internally call printOddNumber or printEvenNumber methods in their run() method....

In the Test.java created one NumHolder objNumHolder and instance of the Odd and Even class(o1, e1).
Start both the treads by calling o1.start() and e1.start()...
In the o1.run() its calling printOddNumber(String threadName)
And in the e1.run()its calling printEvenNumber(String threadName)

Initially isEven variables value is false. So even if the printEvenNumber method from e1 is executed before printOddNumber from o1 it will wait. So e1 will wait till the isEven is changed to true. So the o1's printOddNumber will get executed and it will print the statement...
after that we are changing boolean status of the isEven to true. And calling notifyAll.
So waiting thread of e1 will go ahead and print its value.

Hope this clarified.

Regards,
Purvesh
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Cool! Let's make it harder. Can you do it with only one runnable class and only one print method? That's where I was trying to go ... and not having any great ideas yet.
Timmy Marks
Ranch Hand

Joined: Dec 01, 2003
Posts: 226
maybe a static counter, two parameters (just in case we need it for threads that should only print when the num is (1 % 3) .....

call them i and j. the thread should only print (and notifyAll()) when
(counter == (i % j))

otherwise it calls wait().

just a couple of thoughts...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Odd-Even Number print program
 
Similar Threads
Help needed with GridLayout example
Assignment 2 - question on string
"assert i%2==0 : i--;"question required
beginning methods help
Quick question regarding System.exit()