-
Notifications
You must be signed in to change notification settings - Fork 0
/
assignment_42.java
63 lines (53 loc) · 1.4 KB
/
assignment_42.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class MyRunnable implements Runnable
{
private int start;
private int end;
private int sum;
public MyRunnable(int start, int end)
{
this.start = start;
this.end = end;
}
@Override
public void run()
{
for (int i = start; i <= end; i += 2)
{
sum += i;
}
}
public int getSum()
{
return sum;
}
}
public class assignment_42
{
private static int N = 1000;
private static int sumParent = 0;
private static int sumChild = 0;
public static void main(String[] args)
{
MyRunnable parentRunnable = new MyRunnable(1, N);
MyRunnable childRunnable = new MyRunnable(0, N);
Thread parentThread = new Thread(parentRunnable);
Thread childThread = new Thread(childRunnable);
parentThread.start();
childThread.start();
try
{
parentThread.join();
childThread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
sumParent = parentRunnable.getSum();
sumChild = childRunnable.getSum();
int totalSum = sumParent + sumChild;
System.out.println("Sum of odd numbers (Parent Thread): " + sumParent);
System.out.println("Sum of even numbers (Child Thread): " + sumChild);
System.out.println("Total Sum: " + totalSum);
}
}