You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.
However, you can use join()
to wait for a thread to complete its work.
For example, in your case
ob1.t.join();
This statement will not return until thread 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 wait for thread t
to finish.
NOTE that t.join
did not do anything to thread t
or to thread t1
. It only affected the thread that called it (i.e., the main()
thread).
Edited:
t.join();
needs to be inside the try
block because it throws
the InterruptedException
exception, otherwise you will get an error at compile time. So, it should be:
try{
t.join();
}catch(InterruptedException e){
// ...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…