Created
March 1, 2016 20:38
-
-
Save avraamisvi/ebc290191138f3d4dd03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
/** com um array e wai e notify */ | |
public class ProducerConsumer { | |
static class Producer implements Runnable { | |
private int[] items; | |
public Producer(int[] items) { | |
this.items = items; | |
} | |
@Override | |
public void run() { | |
Random rand = new Random(); | |
while(true) { | |
synchronized (items) { | |
// System.out.println("Fabricando"); | |
for(int i = 0; i < this.items.length; i++) { | |
this.items[i] = rand.nextInt(100)+1; | |
} | |
items.notify(); | |
} | |
// System.out.println("Terminou de fabricar"); | |
} | |
} | |
} | |
static class Consumer implements Runnable { | |
private int[] items; | |
public Consumer(int[] items) { | |
this.items = items; | |
} | |
@Override | |
public void run() { | |
synchronized (items) { | |
try { | |
while(true) { | |
while(this.items[0] == 0) { | |
this.items.wait(); | |
} | |
System.out.println("Consumindo"); | |
for(int i = 0; i < this.items.length; i++) { | |
System.out.println(this.items[i]); | |
this.items[i] = 0; | |
} | |
System.out.println("Terminou"); | |
} | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
int[] items = new int[20]; | |
Producer prod = new Producer(items); | |
Consumer cons = new Consumer(items); | |
ExecutorService executorService = Executors.newFixedThreadPool(2); | |
executorService.execute(prod); | |
executorService.execute(cons); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment