-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumTask.java
More file actions
65 lines (51 loc) · 1.7 KB
/
SumTask.java
File metadata and controls
65 lines (51 loc) · 1.7 KB
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
64
65
package basic;
public class SumTask {
private long startRange, endRange;
private long sum;
private static final long RANGE = Integer.MAX_VALUE;
public SumTask(long startRange, long endRange) {
this.startRange = startRange;
this.endRange = endRange;
}
public long getSum() {
for(long i = startRange; i <= endRange; i++) {
sum += i;
}
return sum;
}
static public void singleThreadSum() {
System.out.println("Single thread sum starting..");
long start = System.currentTimeMillis();
SumTask sumTask = new SumTask(1, RANGE);
sumTask.getSum();
long end = System.currentTimeMillis();
System.out.println("Single thread sum took " + (end - start) + " ms");
}
static public void multiThreadSum() {
System.out.println("Multi thread sum starting..");
long start = System.currentTimeMillis();
SumTask sumTask1 = new SumTask(1, RANGE / 2);
SumTask sumTask2 = new SumTask(RANGE / 2 + 1, RANGE);
Thread thread1 = new Thread(sumTask1::getSum);
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
sumTask2.getSum();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Multi thread sum took " + (end - start) + " ms");
}
public static void main(String[] args) {
singleThreadSum();
multiThreadSum();
}
}