@@ -11,30 +11,83 @@ public static void main(String[] args) {
1111
1212 int countP = Integer .parseInt (args [1 ]);
1313 int countC = Integer .parseInt (args [2 ]);
14+ int T = Integer .parseInt (args [3 ]);
1415
15- Producer p = new Producer ( storage );
16- Consumer c = new Consumer ( storage );
16+ ExecutorService serviceP = Executors . newFixedThreadPool ( countP );
17+ ExecutorService serviceC = Executors . newFixedThreadPool ( countC );
1718
18- List <Future <?>> futures = new ArrayList <>();
19+ List <Future <?>> futuresP = new ArrayList <>();
20+ List <Future <?>> futuresC = new ArrayList <>();
1921
20- try (ExecutorService service = Executors .newCachedThreadPool ()) {
21- for (int i = 0 ; i < countP ; ++i ) {
22- futures .add (service .submit (p ));
22+ CommonRes resP = new CommonRes ();
23+ CommonRes resC = new CommonRes ();
24+
25+ for (int i = 0 ; i < countP ; ++i ) {
26+ futuresP .add (serviceP .submit (new Producer (storage , resP )));
27+ }
28+
29+ for (int i = 0 ; i < countC ; ++i ) {
30+ futuresC .add (serviceC .submit (new Consumer (storage , resC )));
31+ }
32+
33+ synchronized (Thread .currentThread ()) {
34+ try {
35+ Thread .currentThread ().wait (T * 1000L );
36+ } catch (InterruptedException e ) {
37+ throw new RuntimeException (e );
2338 }
39+ }
2440
25- for (int i = 0 ; i < countC ; ++i ) {
26- futures .add (service .submit (c ));
41+ serviceP .shutdown ();
42+ resP .setFlag (false );
43+
44+ while (true ) {
45+ if (Check .start (futuresP )) {
46+ synchronized (Thread .currentThread ()) {
47+ try {
48+ Thread .currentThread ().wait (100 );
49+ } catch (InterruptedException e ) {
50+ throw new RuntimeException (e );
51+ }
52+ }
53+ } else {
54+ System .out .println ("Producer's are finished" );
55+ break ;
2756 }
57+ }
2858
29- synchronized (Thread .currentThread ()) {
30- Thread .currentThread ().wait (1000 );
59+ while (true ) {
60+ if (!storage .isEmpty ()) {
61+ synchronized (Thread .currentThread ()) {
62+ try {
63+ Thread .currentThread ().wait (100 );
64+ } catch (InterruptedException e ) {
65+ throw new RuntimeException (e );
66+ }
67+ }
68+ } else {
69+ System .out .println ("Storage is empty" );
70+ break ;
3171 }
72+ }
3273
33- if (Check .start (futures )) {
34- service .shutdownNow ();
74+ serviceC .shutdown ();
75+ resC .setFlag (false );
76+
77+ if (Check .start (futuresC )) {
78+ try {
79+ if (!serviceC .awaitTermination (10 , TimeUnit .SECONDS )) {
80+ serviceC .shutdownNow ();
81+ if (!serviceC .awaitTermination (10 , TimeUnit .SECONDS )) {
82+ System .err .println ("Pool did not terminate" );
83+ }
84+ }
85+ } catch (InterruptedException ex ) {
86+ serviceC .shutdownNow ();
87+ Thread .currentThread ().interrupt ();
3588 }
36- } catch (InterruptedException ex ) {
37- System .err .println (ex .getLocalizedMessage ());
3889 }
90+
91+ System .out .println ("Consumer's are finished" );
3992 }
40- }
93+ }
0 commit comments