Syntax:
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.
output:
//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.
output:
Using getName(), setName(String) and getId() method:
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:
The currentThread() method returns a reference to the currently executing thread object.
output:
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…