Click to See Complete Forum and Search --> : join()


Abalfazl
January 6th, 2010, 11:12 AM
public class Main {

public static void main(String[] args){

new SimpleThread("Fiji").start();
Thread a=new SimpleThread("Jamaica");
a.start();
try{
a.join();
}
catch (InterruptedException ie) {
System.out.println(ie.getMessage());
}




}

}

class SimpleThread extends Thread {


public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 7; i++) {
System.out.println(i + " " + getName());


}
System.out.println("DONE! " + getName());
}
}





Output of this program:

0 Fiji
0 Jamaica
1 Fiji
1 Jamaica
2 Jamaica
2 Fiji
3 Fiji
4 Fiji
3 Jamaica
5 Fiji
4 Jamaica
6 Fiji
5 Jamaica
DONE! Fiji
6 Jamaica
DONE! Jamaica

http://www.edumax.com/java-basics-thread-join.html
Using A.join() within a thread is tantamount to making the current thread sleep until thread 'A' completes execution.

In this program , a.join must cause another thread stops , until a dies.

Then the output must be this :


0 Jamaica
1 Jamaica
2 Jamaica
3 Jamaica
4 Jamaica
......

Why isn't that?

Deliverance
January 6th, 2010, 02:00 PM
Here's what I see:

0 Jamaica
1 Jamaica
2 Jamaica
3 Jamaica
4 Jamaica
5 Jamaica
6 Jamaica
DONE! Jamaica
0 Fiji
1 Fiji
2 Fiji
3 Fiji
4 Fiji
5 Fiji
6 Fiji
DONE! Fiji

keang
January 8th, 2010, 05:20 PM
The output could be in any order at all and isn't even guaranteed to be the same each time you run it.

Your code isn't doing what you think it is. The call to a.join() is from the Main thread and therefore it stops the Main thread and not the Fiji thread. Therefore, both your created threads are still running and so will print out as and when they get the execution context.

If you want the Fiji thread to stop you must get the Fiji thread to call a.join().

Abalfazl
January 8th, 2010, 09:41 PM
public class Main {

public static void main(String[] args){


Thread a=new SimpleThread("Jamaica");
a.start();
try{
a.join();
}
catch (InterruptedException ie) {
System.out.println(ie.getMessage());
}
new SimpleThread("Fiji").start();


}

}



It is better way!

dlorde
January 9th, 2010, 06:12 AM
Why use threads at all if you want them to run consecutively? Threads are for concurrent tasks.

Hardware: The parts of a computer system that can be kicked...
Jeff Pesis