11package prodcons ;
22
3+ import java .util .Arrays ;
4+ import java .util .concurrent .ArrayBlockingQueue ;
5+ import java .util .concurrent .BlockingQueue ;
6+
37public class ProducerConsumer {
48 public static void main (String [] args ) {
59 // need a shared BlockingQueue<int[]>
10+ BlockingQueue <int []> bq = new ArrayBlockingQueue <>(10 );
611
712 Runnable producer = () -> {
813/*
@@ -15,6 +20,21 @@ public static void main(String[] args) {
1520 5) overwrite our array pointer with null
1621 6) loop around
1722*/
23+ try {
24+ for (int i = 0 ; i < 10_000 ; i ++) {
25+ int [] data = {0 , i };
26+ if (i < 500 ) {
27+ Thread .sleep (1 );
28+ }
29+ data [0 ] = i ;
30+ if (i == 5_000 ) {
31+ data [0 ] = -1 ;
32+ }
33+ bq .put (data );
34+ }
35+ } catch (InterruptedException ie ) {
36+ System .out .println ("this shouldn't happen..." );
37+ }
1838 };
1939
2040 Runnable consumer = () -> {
@@ -25,10 +45,27 @@ public static void main(String[] args) {
2545 3) verify that the array contains { count, count } -- message if not
2646 4) loop around
2747 */
48+ try {
49+ for (int i = 0 ; i < 10_000 ; i ++) {
50+ int [] data = bq .take ();
51+ if (data [0 ] != i || data [0 ] != data [1 ]) {
52+ System .out .println ("***** Error at index " + i + " got " + Arrays .toString (data ));
53+ }
54+ if (i > 9_500 ) {
55+ Thread .sleep (1 );
56+ }
57+ }
58+ } catch (InterruptedException ie ) {
59+ System .out .println ("shouldn't happen" );
60+ }
61+
2862 };
2963
3064 // create two threads
3165 // start both
3266 // optionally--join both.
67+ new Thread (producer ).start ();
68+ new Thread (consumer ).start ();
69+
3370 }
3471}
0 commit comments