public void join() throws InterruptedException public void join(long miliseconds) throws InterruptedException
class JoinDemo extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
System.out.println("Dinesh on Java "+i);
}
}
public static void main(String args[]){
JoinDemo t1 = new JoinDemo();
JoinDemo t2 = new JoinDemo();
JoinDemo t3 = new JoinDemo();
t1.start();
try{
t1.join();
}catch(Exception e){
System.out.println(e);
}
t2.start();
t3.start();
}
}
As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
//Example of join(long miliseconds) method
class JoinDemo extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
System.out.println("Dinesh on Java "+i);
}
}
public static void main(String args[]){
JoinDemo t1 = new JoinDemo();
JoinDemo t2 = new JoinDemo();
JoinDemo t3 = new JoinDemo();
t1.start();
try{
t1.join(1500);
}catch(Exception e){
System.out.println(e);
}
t2.start();
t3.start();
}
}
In the above example,when t1 is completes its task for 1500 milliseconds(3 times) then t2 and t3 starts executing.
public String getName()//is used to return the name of a thread. public void setName(String name)//is used to change the name of a thread. public long getId()//is used to return the id of a thread.
class JoinDemo extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
System.out.println("Running thread is "+Thread.currentThread().getName()+" : "+i);
}
}
public static void main(String args[]){
JoinDemo t1 = new JoinDemo();
JoinDemo t2 = new JoinDemo();
JoinDemo t3 = new JoinDemo();
t1.setName("Dinesh on Java");
System.out.println("id of t1:"+t1.getId());
System.out.println("id of t2:"+t2.getId());
System.out.println("id of t3:"+t3.getId());
t1.start();
try{
t1.join(1500);
}catch(Exception e){
System.out.println(e);
}
t2.start();
t3.start();
}
}
The currentThread() method:
Labels: multithreading