First rule of threading - "Threading is fun"...
I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where
t.start()
is written but stillrun()
method is not executed rathermain()
method continues execution. So why is this happening?
This is exactly what should happen. When you call Thread#start
, the thread is created and schedule for execution, it might happen immediately (or close enough to it), it might not. It comes down to the thread scheduler.
This comes down to how the thread execution is scheduled and what else is going on in the system. Typically, each thread will be given a small amount of time to execute before it is put back to "sleep" and another thread is allowed to execute (obviously in multiple processor environments, more than one thread can be running at time, but let's try and keep it simple ;))
Threads may also yield
execution, allow other threads in the system to have chance to execute.
You could try
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
// Yield here
Thread.yield();
}
And it might make a difference to the way the threads run...equally, you could sleep
for a small period of time, but this could cause your thread to be overlooked for execution for a period of cycles (sometimes you want this, sometimes you don't)...
join()
method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??
The way you've stated the question is wrong...join
will wait for the Thread
it is called on to die before returning. For example, if you depending on the result of a Thread
, you could use join
to know when the Thread
has ended before trying to retrieve it's result.
Equally, you could poll the thread, but this will eat CPU cycles that could be better used by the Thread
instead...