|
-
January 6th, 2010, 12:12 PM
#1
join()
Code:
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?
-
January 6th, 2010, 03:00 PM
#2
Re: join()
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
------
If you are satisfied with the responses, add to the user's rep!
-
January 8th, 2010, 06:20 PM
#3
Re: join()
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().
-
January 8th, 2010, 10:41 PM
#4
Re: join()
Code:
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!
-
January 9th, 2010, 07:12 AM
#5
Re: join()
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
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|