-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExample4.java
More file actions
114 lines (80 loc) · 2.47 KB
/
Example4.java
File metadata and controls
114 lines (80 loc) · 2.47 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package applications.threading;
import datastructs.maths.Vector;
import java.util.ArrayList;
import java.util.concurrent.*;
/**
* Category: Threading
* ID: Example4
* Description: Illustrates ExecutorService
* Taken From:
*
* Details:
*
*
*/
public class Example4 {
public class LocalResult implements Callable<Double>{
public LocalResult(Vector v, int start, int end){
this.v = v;
this.start = start;
this.end = end;
}
@Override
public Double call(){
double rslt = 0.0;
for(int i=this.start; i<this.end; ++i){
rslt += this.v.get(i);
}
return rslt;
}
Vector v;
int start;
int end;
}
public static boolean tasksFinished(ArrayList<Future<Double>> tasks){
for (int i = 0; i < tasks.size(); i++) {
if(tasks.get(i) != null && !tasks.get(i).isDone()){
return false;
}
}
return true;
}
public static void main(String[] args){
Example4 exe = new Example4();
Vector v = new Vector(200, 1.0);
// number of threads
int numTreads = 4;
int localWorkSize = v.size()/numTreads;
ExecutorService service = Executors.newFixedThreadPool(numTreads);
ArrayList<Future<Double>> rslts = new ArrayList<>();
ArrayList<LocalResult> tasks = new ArrayList<>();
tasks.add(exe.new LocalResult(v, 0, localWorkSize));
tasks.add(exe.new LocalResult(v, localWorkSize, 2*localWorkSize));
tasks.add(exe.new LocalResult(v, 2*localWorkSize, 3*localWorkSize));
tasks.add(exe.new LocalResult(v, 3*localWorkSize, 4*localWorkSize));
for(int i=0; i<tasks.size(); ++i){
rslts.add(service.submit(tasks.get(i)));
}
// wait until tasks are done
while(!Example4.tasksFinished(rslts)){
Thread.yield();
}
double sum = 0.0;
for (Future<Double> rslt: rslts) {
try {
if(rslt != null) {
if (rslt.isDone()) {
sum += rslt.get();
rslt = null;
}
}
}
catch(ExecutionException e){
}
catch(InterruptedException e){
}
}
System.out.println("Sum of array elements is: "+sum);
service.shutdownNow();
}
}