Created
August 6, 2014 23:01
-
-
Save deverton/3e509cd4241af475f922 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.BlockingQueue; | |
import java.util.concurrent.LinkedBlockingQueue; | |
public class Demo { | |
private static final Random R = new Random(); | |
static class Producer implements Runnable { | |
private final BlockingQueue<Integer> queue; | |
Producer(BlockingQueue<Integer> queue) { | |
this.queue = queue; | |
} | |
@Override | |
public void run() { | |
try { | |
while (true) { | |
queue.put(R.nextInt()); | |
} | |
} catch (InterruptedException ie) { | |
System.err.println("Shutting down producer"); | |
} | |
} | |
} | |
static class Consumer implements Runnable { | |
private final BlockingQueue<Integer> queue; | |
Consumer(BlockingQueue<Integer> queue) { | |
this.queue = queue; | |
} | |
@Override | |
public void run() { | |
try { | |
while (true) { | |
System.out.println(Thread.currentThread().getName() + " - got " + queue.take()); | |
System.out.flush(); | |
} | |
} catch (InterruptedException ie) { | |
System.err.println("Shutting down consumer"); | |
} | |
} | |
} | |
public static void main(String... args) throws Exception { | |
BlockingQueue q = new LinkedBlockingQueue(); | |
Thread p = new Thread(new Demo.Producer(q)); | |
Thread c1 = new Thread(new Demo.Consumer(q)); | |
Thread c2 = new Thread(new Demo.Consumer(q)); | |
c2.start(); | |
c1.start(); | |
p.start(); | |
// Wait a bit | |
Thread.sleep(1000); | |
c2.interrupt(); | |
c2.join(); | |
p.interrupt(); | |
p.join(); | |
c1.interrupt(); | |
c1.join(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment