Skip to content

Instantly share code, notes, and snippets.

@linkin-park
Created February 11, 2016 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linkin-park/3493161aa4b39aa912ac to your computer and use it in GitHub Desktop.
Save linkin-park/3493161aa4b39aa912ac to your computer and use it in GitHub Desktop.
Java
package com.concurrency;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ITCExist {
private static ConcurrentLinkedQueue<Integer> clQ = new ConcurrentLinkedQueue<>();
static class Producer implements Runnable {
@Override
public void run() {
int i = 0;
while (true) {
clQ.add(i);
System.out.println("produced i"+i++);
synchronized (clQ) {
clQ.notify();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
synchronized (clQ) {
if (clQ.isEmpty())
try {
clQ.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = clQ.poll();
System.out.println("consumed i "+i);
}
}
}
}
public static void main(String[] args) throws InterruptedException{
Thread prod = new Thread(new Producer(), "prod");
Thread cons = new Thread(new Consumer(), "cons");
cons.start();
prod.start();
cons.join();
prod.join();
System.out.println("Completed!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment