Created
February 11, 2016 10:38
-
-
Save linkin-park/3493161aa4b39aa912ac to your computer and use it in GitHub Desktop.
Java
This file contains 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
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