start() Method & join() Method in Multithreading in JAVA.(Three threads should calculate the sum of 1 to 5, 6 to 10 and 11 to 15)
In this example every run() function in class S.O.P print some statement,this statement do not require program ,but when the execution program to understand how to work Multi Threading.
After all thread finishes main thread should print the sum and average.
import java.lang.Thread;
class first extends Thread
{
int sum=0,i;
public void run() {
for(i=1;i<6;i++) {
System.out.println("First:" + ((i==5) ? (i+" SUM "+(sum+i)+" End First") : (i+" SUM "+(sum+i))));
sum=sum+i;
}
}
}
class second extends first
{
public void run() {
for(i=6;i<11;i++) {
System.out.println("Second:" + ((i==10) ? (i+" SUM "+(sum+i)+" End Second") : (i+" SUM "+(sum+i))));
sum=sum+i;
}
}
}
class third extends second
{
public void run(){
for(i=11;i<16;i++) {
System.out.println("Third:" + ((i==15) ? (i+" SUM "+(sum+i)+" End Third") : (i+" SUM "+(sum+i))));
sum=sum+i;
}
}
}
class main
{
public static void main(String [] args) {
first sum1=new first();
second sum2=new second();
third sum3=new third();
sum1.start(); //execution the thread
sum2.start();
sum3.start();
try{ //join() Method is always in try-catch block round it, because it can throw an InterruptedException
sum1.join(); //join() method waits until the thread it joins with completes its task.
sum2.join(); //join() method pause main thread statement
sum3.join();
}
catch(Exception e){ }
System.out.print("Sum : "+(sum1.sum+sum2.sum+sum3.sum)+" Average : "+((sum1.sum+sum2.sum+sum3.sum)/3));
}
}
class first extends Thread
{
int sum=0,i;
public void run() {
for(i=1;i<6;i++) {
System.out.println("First:" + ((i==5) ? (i+" SUM "+(sum+i)+" End First") : (i+" SUM "+(sum+i))));
sum=sum+i;
}
}
}
class second extends first
{
public void run() {
for(i=6;i<11;i++) {
System.out.println("Second:" + ((i==10) ? (i+" SUM "+(sum+i)+" End Second") : (i+" SUM "+(sum+i))));
sum=sum+i;
}
}
}
class third extends second
{
public void run(){
for(i=11;i<16;i++) {
System.out.println("Third:" + ((i==15) ? (i+" SUM "+(sum+i)+" End Third") : (i+" SUM "+(sum+i))));
sum=sum+i;
}
}
}
class main
{
public static void main(String [] args) {
first sum1=new first();
second sum2=new second();
third sum3=new third();
sum1.start(); //execution the thread
sum2.start();
sum3.start();
try{ //join() Method is always in try-catch block round it, because it can throw an InterruptedException
sum1.join(); //join() method waits until the thread it joins with completes its task.
sum2.join(); //join() method pause main thread statement
sum3.join();
}
catch(Exception e){ }
System.out.print("Sum : "+(sum1.sum+sum2.sum+sum3.sum)+" Average : "+((sum1.sum+sum2.sum+sum3.sum)/3));
}
}
Comments
Post a Comment