Java Multithreading concept and join() method
You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.
However if you use
join()
,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.
For example, in your case
ob1.t.join();
This will make sure that the current running thread will run only after t has finished running.
Try this,
class Demo { Thread t = new Thread( new Runnable() { public void run () { //do something } } ); Thread t1 = new Thread( new Runnable() { public void run () { //do something } } ); t.start(); // Line 15 t.join(); // Line 16 t1.start(); }
In the above example, your main thread is executing. When it encounters line 15, thread t is available at thread scheduler. As soon as main thread comes to line 16, it will not execute unless thread t has finished( remember
join()
as the currently running thread will join to the end of the thread on which join is called).Hence main thread will come to line 17 only when thread t has finished.
So it may appear that
t.join
will affect thread t1, but it is actually affecting main thread.What is Daemon thread in java
268 |
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
You can use the
setDaemon() method to change the Thread daemon properties.what is difference between sleep method and yield method of multi threading?
|
No comments:
Post a Comment