Thread Part III
Method isAlive and Join
Sometime
in our program we want our main thread be the last one to stop or
finish, after all the child threads finished. For making this happen,
firstly we need to check weather the child threads is alive using
method isAlive(), then we use method join(), that belong to Thread
Class. let’s check how it work first we create thread. As shown
below,
public
class
MyThreadMain implements
Runnable {
private
Thread thread;
private
int
n;
MyThreadMain(String
name, int
n){
thread
= new
Thread(this,
name);
this.n
= n;
}
@Override
public
void
run() {
try
{
for
(int
i = 0; i <n;
i++) {
System.out.println("Thread"+ thread.getName()
+"second: "+(i+1));
Thread.sleep(1000);
}
System.out.println("Thread
"+ thread.getName()
+" finish.... ");
}
catch
(Exception e) {
e.printStackTrace();
}
}
public
void
start(){
thread.start();
}
public
Thread getThread(){
return
thread;
}
}
public
class
IsAliveJoinDemo {
public stati cvoid
main(String[]args)throws InterruptedException{
System.out.println("\nMain
Thread execute....");
MyThreadMain
t1 = new
MyThreadMain("first",
2);
MyThreadMain
t2 = new
MyThreadMain("second",
3);
MyThreadMain
t3 = new
MyThreadMain("third",
3);
t1.start();
t2.start();
t3.start();
System.out.println("t1
is alive ? "+
t1.getThread().isAlive());
System.out.println("t2
is alive ?"+
t2.getThread().isAlive());
System.out.println("t3
is alive ?"+
t3.getThread().isAlive());
t1.getThread().join();
t2.getThread().join();
t3.getThread().join();
System.out.println("t1
is alive ? "+
t1.getThread().isAlive());
System.out.println("t2
is alive ?"+
t2.getThread().isAlive());
System.out.println("t3
is alive ?"+
t3.getThread().isAlive());
System.out.println("\nMain
Thread is executed..");
}
}
Main Thread execute....
t1
is alive ? true
Thread
first second : 1
Thread
second second : 1
Thread
third second : 1
t2
is alive ?true
t3
is alive ?true
Thread
third second : 2
Thread
second second : 2
Thread
first second : 2
Thread
second second : 3
Thread
third second : 3
Thread
first finish....
Thread
third finish....
Thread
second finish....
t1
is alive ? false
t2
is alive ?false
t3
is alive ?false
Main
Thread is executed..
No comments:
Post a Comment