• Post Reply Bookmark Topic Watch Topic
  • New Topic

join() is not executing correctly.

 
Punya Pratap Singh
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class ThreadDemo extends Thread {
public void run() {
for(int i = 0; i < 5; i++) compute();
}
public static void main(String[] args) {
ThreadDemo thread1 = new ThreadDemo();
Thread thread2 = new Thread(new Runnable() {
public void run() { for(int i = 0; i < 5; i++) compute(); }
});

if (args.length >= 1) thread1.setPriority(Integer.parseInt(args[0]));
if (args.length >= 2) thread2.setPriority(Integer.parseInt(args[1]));
thread1.start();
thread2.start();
for(int i = 0; i < 5; i++) compute();

try {
thread1.join();
// thread2.join();
} catch (InterruptedException e) {}
}

static ThreadLocal numcalls = new ThreadLocal();
static synchronized void compute() {
Integer n = (Integer) numcalls.get();
if (n == null) n = new Integer(1);
else n = new Integer(n.intValue() + 1);
numcalls.set(n);
System.out.println(Thread.currentThread().getName() + ": " + n);
for(int i = 0, j=0; i < 1000000; i++) j += i;
try {
System.out.println("Current Thread Executing "+Thread.currentThread());
//Thread.sleep(2000);
//}
//catch (InterruptedException e) {}
Thread.yield();
}
}


As thread1.join() is called so it means that when control reaches to this line.thread1 must end its job first.
but this is not happening in output why ?Please Explain ?


Hi Steve I hope that now you could find the code formatted please go through It and Expalin ?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Punya,

That code is really hard to read. Can you go back and edit your post (there is an edit button on the top write corner of the post) and add code tags (select the code, and press the Code button at the top of the editor). Please also add correct formatting to make the code easy to read.

As thread1.join() is called so it means that when control reaches to this line.thread1 must end its job first.
but this is not happening in output why ?Please Explain ?

It may be the formatting, but I don't see any way the output could show that thread1 was not complete before the main thread moved on to termination. There is no output in the main() method after the thread1.join() call is made, so how would you know if the main thread waited for thread1 to complete or not?
 
prem pillai
Ranch Hand
Posts: 87
Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread1 is getting completed before main thread , as expected.
Actually you are just confused because , you dont have any output printed after the join call in the main thread.




Regards
Prem
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!