1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| @Test public void testProducerConsumer() { List<String> list = Lists.newArrayList(); ReentrantLock lock = new ReentrantLock(); Condition full = lock.newCondition(); Condition empty = lock.newCondition();
ExecutorService executor = new ThreadPoolExecutor(8, 8, 30, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), new ThreadPoolExecutor.DiscardPolicy()); for (int i = 0; i < 4; ++i) { executor.submit(new Producer(list, 100, lock, full, empty)); } for (int i = 0; i < 4; ++i) { executor.submit(new Consumer(list, lock, full, empty)); } while (!executor.isTerminated()) { ; } }
private static class Consumer implements Runnable { private List<String> list; private Lock lock; private Condition full; private Condition empty;
public Consumer(List<String> list, Lock lock, Condition full, Condition empty) { this.list = list; this.lock = lock; this.full = full; this.empty = empty; }
@Override public void run() { while (true) { try { lock.lock(); while (list.isEmpty()) { empty.await(); } String element = list.remove(0); System.out.println(element); full.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }
private static class Producer implements Runnable { private List<String> list; private Integer maxLength; private Random random; private Lock lock; private Condition full; private Condition empty;
public Producer(List<String> list, int maxLength, Lock lock, Condition full, Condition empty) { this.list = list; this.lock = lock; this.maxLength = maxLength; this.random = new Random(System.currentTimeMillis()); this.full = full; this.empty = empty; }
@Override public void run() { while (true) { try { lock.lock(); while (list.size() >= maxLength) { full.await(); } double d = random.nextGaussian(); list.add(Thread.currentThread().getName() + " " + d); empty.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }
|