1
1
package task3 .teastall .server ;
2
2
3
+ import task3 .teastall .Constants ;
4
+
3
5
import java .io .DataOutputStream ;
4
6
import java .io .IOException ;
5
7
import java .net .Socket ;
6
8
import java .time .LocalDateTime ;
7
9
import java .util .Map ;
10
+ import java .util .concurrent .CountDownLatch ;
8
11
9
12
public class OrderProcessor extends Thread {
10
13
private Map <String , Integer > order ;
@@ -28,22 +31,25 @@ public void run() {
28
31
// Create thread for all the items and join on them
29
32
ItemProcessor [] itemProcessors = new ItemProcessor [order .size ()];
30
33
int count = 0 ;
34
+ CountDownLatch latch = new CountDownLatch (order .size ());
35
+
31
36
for (Map .Entry <String , Integer > entry : order .entrySet ()) {
32
- itemProcessors [count ] = new ItemProcessor (server , entry .getKey (), entry .getValue ());
37
+ itemProcessors [count ] = new ItemProcessor (server , entry .getKey (), entry .getValue (), latch );
33
38
itemProcessors [count ].start ();
34
39
count ++;
35
40
}
36
- for (ItemProcessor itemProcessor : itemProcessors ) {
37
- try {
38
- itemProcessor .join ();
39
- int d = itemProcessor .getDelay ();
40
41
41
- // check if the order can be fulfilled or not
42
- if (d < 0 ) available = false ;
43
- if (delay < d ) delay = d ;
44
- } catch (InterruptedException e ) {
45
- e .printStackTrace ();
46
- }
42
+ try {
43
+ latch .await ();
44
+ } catch (InterruptedException e ) {
45
+ e .printStackTrace ();
46
+ }
47
+
48
+ for (ItemProcessor itemProcessor : itemProcessors ) {
49
+ int d = itemProcessor .getDelay ();
50
+ // check if the order can be fulfilled or not
51
+ if (d < 0 ) available = false ;
52
+ if (delay < d ) delay = d ;
47
53
}
48
54
}
49
55
@@ -69,7 +75,7 @@ LocalDateTime sendResult(LocalDateTime timeStamp) {
69
75
timeStamp = timeStamp .plusMinutes (getDelay ());
70
76
try {
71
77
if (dataOutputStream != null ) {
72
- dataOutputStream .writeUTF ("The order will be delivered at " + timeStamp .toString () + "." );
78
+ dataOutputStream .writeUTF ("The order will be delivered by " + timeStamp .format ( Constants . DATE_TIME_FORMATTER ) );
73
79
}
74
80
} catch (IOException e ) {
75
81
e .printStackTrace ();
0 commit comments