-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqrt_v2.java
More file actions
77 lines (65 loc) · 2.4 KB
/
Sqrt_v2.java
File metadata and controls
77 lines (65 loc) · 2.4 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
66
67
68
69
70
71
72
73
74
75
76
77
//
// SquareRoot Java Program
// This program spawns children, who will help to determine square roots.
// To compile: javac SquareRoot.java
// To run: java SquareRoot
// To monitor system resources: (Linux): Applications->System Tools->System Monitor->Resources
// Use Spreadsheet Applications->Office->LibreOffice Calc to show efficiency of multiple threads.
//
import java.lang.Math;
import java.lang.Thread;
import java.util.ArrayList;
import java.util.List;
class SquareRoot {
public static void main(String[] args) {
final int numChild = 1000;
final int total = 200000;
double range = total/numChild;
double begin=0.0;
List<Thread> threads = new ArrayList<Thread>();
System.out.println("Total: " + total);
//System.out.println("Run SquareRoot " + total + ":" + numChild);
// Spawn children processes
for (int i=0; i<numChild; i++) {
Thread t = new Thread(new SquareChild(begin, begin+range));
t.start();
threads.add(t);
begin += range + 1;
}
// Wait for children to finish
for (Thread t : threads) {
try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); }
}
System.out.println("All Children Done: " + numChild);
}
}
class SquareChild implements Runnable {
private double begin;
private double end;
double memAttr;
double global;
public SquareChild(double begin, double end) {
this.begin = begin;
this.end = end;
}
@Override
public void run() {
// Print the current CPU number
//System.out.println("CPU=" + Thread.currentThread().getName());
// Get the current time
long start_s = System.currentTimeMillis();
double totalSum = 0.0;
for (int local = (int)begin; local < end; local++) {
double root = Math.sqrt(local);
// revised lines to do prints:
// System.out.println(local + ":" + root + " ");
// if (local%5==0) System.out.println();
// totalSum += root;
}
// Are class attributes and globals shared?
//System.out.println(" totalSum=" + totalSum + " global=" + ++global + " memAttr=" + ++memAttr);
// Calculate execution time in ms and print
long stop_s = System.currentTimeMillis();
//System.out.println("time: " + (stop_s - start_s));
}
}