Skip to content

Instantly share code, notes, and snippets.

@mahbodkh
Created August 22, 2017 14:12
Show Gist options
  • Select an option

  • Save mahbodkh/286d437909b8c4b3608fcc53719d7c61 to your computer and use it in GitHub Desktop.

Select an option

Save mahbodkh/286d437909b8c4b3608fcc53719d7c61 to your computer and use it in GitHub Desktop.
package thread;
import java.util.ArrayList;
import java.util.List;
class Producer extends Thread {
private final List<Integer> list;
Producer(List<Integer> list) {
this.list = list;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Integer num = (int) (Math.random() * 1000);
synchronized (list) {
System.out.println("Added:" + num);
list.add(num);
list.notify();
}
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) { /**/
}
}
}
}
class Consumer extends Thread {
private final List<Integer> list;
public Consumer(List<Integer> list) {
this.list = list;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized (list) {
while (list.size() == 0) {
try {
list.wait();
} catch (InterruptedException e) { /**/
}
Integer fetch = list.remove(0);
System.err.println("Fetched:" + fetch);
}
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) throws InterruptedException {
List<Integer> list = new ArrayList<>();
Thread[] threads = {
new Producer(list), new Producer(list),
new Consumer(list), new Consumer(list)
};
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("Finished: " + list.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment