3/3/08

Java Thread Example

You can see bellow two different programs which actually print all the numbers from 1-5000.

Count program one

class Count1 {
public static void main(String[] args) {
for (int i=0;i<=5000;i++) {
System.out.println(" i= "+i);
}
}
}

Count program two

class Count2 extends Thread {
int from,to;
public Count2(int from,int to) {
this.from=from;
this.to=to;
}

public void run() {
for(int i=from;i<=to;i++) {
System.out.println(" i = "+i);
}
}

public static void main(String[] args) {
for(int i=0;i<10;i++) {
Count2 t =new Count2(i*500,(i+1)*500);
t.start();
}
}
}


Now i must a say a few words.
Count program one it is just a for loop from 0 to 5000 and each time prints the value of the index i. Prints all the numbers in row.

Count program two also counts from 0 to 5000 but how? It creates ten threads and each one prints 500 numbers. The i thread prints from i*500 to (i+1)*500. Total from 0 to 5000. This time you are not sure about the result...

Now run these two programs and see the results. You will be surprised from the second program which almost every time gives different result.
Do you know why?

No comments: