Skip to content

Instantly share code, notes, and snippets.

@BT-ICD
Created April 19, 2021 11:08
Show Gist options
  • Save BT-ICD/1479704aff4411b9b9f91b9bdd70fac2 to your computer and use it in GitHub Desktop.
Save BT-ICD/1479704aff4411b9b9f91b9bdd70fac2 to your computer and use it in GitHub Desktop.
Example of Thread.join
package ThreadDemoForWait;
public class FactThread implements Runnable{
int i, fact=1;
@Override
public void run() {
for (int i = 1; i <=5 ; i++) {
fact*=i;
System.out.println("\nFactorial of " + i + " = " + fact);
}
}
}
package ThreadDemoForWait;
/*
* SumThread class to process sum of first 5 natural numbers.
* */
public class SumThread implements Runnable{
int i, sum=0;
@Override
public void run() {
for (int i = 1; i <=5 ; i++) {
sum+=i;
System.out.println("\nSum of number from 1 to " + i+ " =" + sum);
}
}
}
package ThreadDemoForWait;
/*
* In some problems, it may be required to wait for a particular thread to complete its task before another thread to proceed with.
* In such occasions, the join method of Thread class can be used.
* When join method is call on a thread object the control waits for the thread to complete its task and becomes a dead thread.
* The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join();
* Reference:
* https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
* Programming in JAVA2 Dr. K. Somasundaram
causes the current thread to pause execution until t's thread terminates.
* */
public class ThreadJoinDemo {
public static void main(String[] args) {
SumThread st = new SumThread();
FactThread ft = new FactThread();
Thread sumt = new Thread(st,"Sum Thread");
Thread factt = new Thread(ft,"Fact Thread");
sumt.setPriority(Thread.NORM_PRIORITY-3);
factt.setPriority(Thread.NORM_PRIORITY+3);
sumt.start();
try {
sumt.join();
} catch (InterruptedException e) {
System.out.println(e.toString());;
}
factt.start();
}
}
@BT-ICD
Copy link
Author

BT-ICD commented Apr 19, 2021

Sample Output:
Sum of number from 1 to 1 =1

Sum of number from 1 to 2 =3

Sum of number from 1 to 3 =6

Sum of number from 1 to 4 =10

Sum of number from 1 to 5 =15

Factorial of 1 = 1

Factorial of 2 = 2

Factorial of 3 = 6

Factorial of 4 = 24

Factorial of 5 = 120

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment