1
+ package com .dev .thread ;
2
+
3
+ import java .math .BigInteger ;
4
+
5
+ public class ComplexCalculationThreadJoin {
6
+ public BigInteger calculateResult (BigInteger base1 , BigInteger power1 , BigInteger base2 , BigInteger power2 ) {
7
+ BigInteger result ;
8
+ /*
9
+ Calculate result = ( base1 ^ power1 ) + (base2 ^ power2).
10
+ Where each calculation in (..) is calculated on a different thread
11
+ */
12
+ PowerCalculatingThread thread1 = new PowerCalculatingThread (base1 , power1 );
13
+ PowerCalculatingThread thread2 = new PowerCalculatingThread (base2 , power2 );
14
+
15
+ thread1 .start ();
16
+ thread2 .start ();
17
+
18
+ try {
19
+ thread1 .join (); // Wait for thread1 to complete
20
+ thread2 .join (); // Wait for thread2 to complete
21
+ } catch (InterruptedException e ) {
22
+ Thread .currentThread ().interrupt ();
23
+ return BigInteger .ZERO ; // Or handle error appropriately
24
+ }
25
+
26
+ result = thread1 .getResult ().add (thread2 .getResult ());
27
+
28
+ return result ;
29
+ }
30
+
31
+ private static class PowerCalculatingThread extends Thread {
32
+ private BigInteger result = BigInteger .ZERO ; // Changed default from ONE to ZERO
33
+ private final BigInteger base ; // Made final
34
+ private final BigInteger power ; // Made final
35
+
36
+ public PowerCalculatingThread (BigInteger base , BigInteger power ) {
37
+ this .base = base ;
38
+ this .power = power ;
39
+ }
40
+
41
+ @ Override
42
+ public void run () {
43
+ /*
44
+ Implement the calculation of result = base ^ power
45
+ */
46
+ result = base .pow (power .intValueExact ()); // Changed from Math.pow to BigInteger.pow
47
+ }
48
+
49
+ public BigInteger getResult () {
50
+ return result ;
51
+ }
52
+ }
53
+
54
+ // For testing
55
+ public static void main (String [] args ) {
56
+ ComplexCalculationThreadJoin calc = new ComplexCalculationThreadJoin ();
57
+ BigInteger result = calc .calculateResult (
58
+ BigInteger .valueOf (100 ),
59
+ BigInteger .valueOf (30 ),
60
+ BigInteger .valueOf (30 ),
61
+ BigInteger .valueOf (209 )
62
+ );
63
+ System .out .println (result ); // Should print 17 (2³ + 3² = 8 + 9 = 17)
64
+ }
65
+ }
0 commit comments