⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 puttaketest.java

📁 java concurrency in practice 源码. JAVA并发设计
💻 JAVA
字号:
package net.jcip.examples;import java.util.concurrent.*;import java.util.concurrent.atomic.*;import junit.framework.TestCase;/** * PutTakeTest * <p/> * Producer-consumer test program for BoundedBuffer * * @author Brian Goetz and Tim Peierls */public class PutTakeTest extends TestCase {    protected static final ExecutorService pool = Executors.newCachedThreadPool();    protected CyclicBarrier barrier;    protected final SemaphoreBoundedBuffer<Integer> bb;    protected final int nTrials, nPairs;    protected final AtomicInteger putSum = new AtomicInteger(0);    protected final AtomicInteger takeSum = new AtomicInteger(0);    public static void main(String[] args) throws Exception {        new PutTakeTest(10, 10, 100000).test(); // sample parameters        pool.shutdown();    }    public PutTakeTest(int capacity, int npairs, int ntrials) {        this.bb = new SemaphoreBoundedBuffer<Integer>(capacity);        this.nTrials = ntrials;        this.nPairs = npairs;        this.barrier = new CyclicBarrier(npairs * 2 + 1);    }    void test() {        try {            for (int i = 0; i < nPairs; i++) {                pool.execute(new Producer());                pool.execute(new Consumer());            }            barrier.await(); // wait for all threads to be ready            barrier.await(); // wait for all threads to finish            assertEquals(putSum.get(), takeSum.get());        } catch (Exception e) {            throw new RuntimeException(e);        }    }    static int xorShift(int y) {        y ^= (y << 6);        y ^= (y >>> 21);        y ^= (y << 7);        return y;    }    class Producer implements Runnable {        public void run() {            try {                int seed = (this.hashCode() ^ (int) System.nanoTime());                int sum = 0;                barrier.await();                for (int i = nTrials; i > 0; --i) {                    bb.put(seed);                    sum += seed;                    seed = xorShift(seed);                }                putSum.getAndAdd(sum);                barrier.await();            } catch (Exception e) {                throw new RuntimeException(e);            }        }    }    class Consumer implements Runnable {        public void run() {            try {                barrier.await();                int sum = 0;                for (int i = nTrials; i > 0; --i) {                    sum += bb.take();                }                takeSum.getAndAdd(sum);                barrier.await();            } catch (Exception e) {                throw new RuntimeException(e);            }        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -