Yes, we can.
But if we do so then we must be aware that run( ) will not execute in separate call stack in this case. Rather it executes onto the current call stack.
Lets have a look at the below example:
In the above example we can see that even though there is sleep() called but context switching doesn't happen. Because both thread object thread1 and thread2 run in current call stack(i.e main stack). So on directly calling run(), thread1 and thread2 are treated as normal object and not the thread object. That is why, first thread1 completes its execution(0,1,2) is printed and then run() of thread2 gets chance to execute.
Now call start() on both the thread and see the difference. You will notice both thread object running in separate call stack and also going through context-switching. Look at below example:
Here we can also see that we don't need to call run() on thread instance as we did in our first example. start() does this task internally.
You may also want to know about:
But if we do so then we must be aware that run( ) will not execute in separate call stack in this case. Rather it executes onto the current call stack.
Lets have a look at the below example:
Separate call stack not allotted to thread1 and thread2 on directly calling run() |
In the above example we can see that even though there is sleep() called but context switching doesn't happen. Because both thread object thread1 and thread2 run in current call stack(i.e main stack). So on directly calling run(), thread1 and thread2 are treated as normal object and not the thread object. That is why, first thread1 completes its execution(0,1,2) is printed and then run() of thread2 gets chance to execute.
Now call start() on both the thread and see the difference. You will notice both thread object running in separate call stack and also going through context-switching. Look at below example:
Calling start() on thread internally calls run() |
Here we can also see that we don't need to call run() on thread instance as we did in our first example. start() does this task internally.
You may also want to know about:
No comments:
Post a Comment