Implementing the join ()

Example program:

Class thread 1 extends thread

{

Int sum;

Public void run ()

{

System. Out. Prinln(“ beginning of run of thread 1 “);

For( int i=0; i< 37; i++)

{

Sum = sum +i;

System. Out. Prinln(“ run of thread1 : “ +i);

}

}

}

Class thread 2 extends thread

{

Public void run ()

{

For (int i=0; i< 137; i++)

System. Out. Prinln(“ run of thread 2 : “ +i);

}

}

Class thread 3 extends thread

{

Thread1 t1;

Thread3 (Thread1 t1)

{

this. t1 = t1;

}

Public void run ()

{

For (int i=400; i< 437; i++)

{

System. Out. Prinln(“ run of thread 3 : “ +i);

If( i==422)

{

Try

{

t1. Join ();

}

Catch (Exception e)

{

System. Out. Prinln(e);

}

Int x = t1.sum – I;

System. Out. Prinln(“ sum :” + t1 . sum);

System. Out. Prinln(“ difference : “ +x);

}

}

}

Class Join Test

{

Public static void main (string args [ ])

{

Thread 1 t1 = new Thread1 ();

Thread 2 t2 = new Thread2 ();

Thread 3 t3 = new Thread3 (t1);

t1. Start ();

t2. Start ();

t3. Start ();

}

}

Explanation:

We know that join () method is used to suspend a thread conditionally. In the above example also, we did the same. We want to sum value which is calculated in thread1 to be used in thread3. In thread3, we call join off on Thread1. Functionality of join () is to check whether run () of t1 is completely executed or not. As long as run () of t1 is not completely executed, control will not come out of it. Thus, thread3 i.e. t3 will be under suspension once control comes out of run () of t1, then it starts executing the statements present in the run () method of current thread (in this case it is t3).

Implementing the Join Homework Help