Tuesday, March 22, 2011

Printing number series with multiple threads

Problem: Write a code to print numbers 1 to 10 with using two threads such that one thread prints 1, 3, 5, 7, 9 and other thread prints 2, 4, 6, 8, 10


Solution:
Below is the code I wrote first but do not believe it to be an elegant solution, I plan to write a more elegant solution later but let's see when it happens.
With this solution, I ran into an issue when I used Integer class instead of MyInteger, could you spot the issue?

 public class AlternatePrint implements Runnable {  
int id;
MyInteger number;
// Integer number;
AlternatePrint(int id, MyInteger number) {
this.id = id;
this.number = number;
}
public void run() {
int last = id;
while (number.getValue() <= 10) {
synchronized (number) {
if (last != number.getValue()) {
System.out.println("Thread: " + id + " printing: "
+ number.getValue());
number.setValue(number.getValue() + 1);
last = number.getValue();
// number++;
// last = number;
}
try {
number.wait(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("Thread: " + id + " exiting!!!");
}
public static void main(String[] args) {
AlternatePrint a, b;
MyInteger o = new MyInteger(1);
a = new AlternatePrint(1, o);
b = new AlternatePrint(2, o);
new Thread(a).start();
new Thread(b).start();
System.out.println("Main Thread exiting!!!");
}
}
class MyInteger {
private int value;
MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

No comments:

Post a Comment