java並發編程(5)並發程式測試,java並發

來源:互聯網
上載者:User

java並發編程(5)並發程式測試,java並發
並發程式測試 一、正確性測試

  如:對一個自訂緩衝的測試

//自訂的緩衝public class SemaphoreBoundedBuffer <E> {    private final Semaphore availableItems, availableSpaces;    private final E[] items;    private int putPosition = 0, takePosition = 0;    public SemaphoreBoundedBuffer(int capacity) {        if (capacity <= 0)            throw new IllegalArgumentException();        availableItems = new Semaphore(0);        availableSpaces = new Semaphore(capacity);        items = (E[]) new Object[capacity];    }    public boolean isEmpty() {        return availableItems.availablePermits() == 0;    }    public boolean isFull() {        return availableSpaces.availablePermits() == 0;    }    public void put(E x) throws InterruptedException {        availableSpaces.acquire();        doInsert(x);        availableItems.release();    }    public E take() throws InterruptedException {        availableItems.acquire();        E item = doExtract();        availableSpaces.release();        return item;    }    private synchronized void doInsert(E x) {        int i = putPosition;        items[i] = x;        putPosition = (++i == items.length) ? 0 : i;    }    private synchronized E doExtract() {        int i = takePosition;        E x = items[i];        items[i] = null;        takePosition = (++i == items.length) ? 0 : i;        return x;    }}//無需比較每次 生產者和消費者取出的值;只需要最終比較和即可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);   //初始化為 線程數量*2 + 1:生產者+消費者+主線程    }    void test() {        try {            for (int i = 0; i < nPairs; i++) {                pool.execute(new Producer());                pool.execute(new Consumer());            }            barrier.await(); // 等待所有線程初始化完成,完成後複位柵欄            barrier.await(); // 等待所有線程執行完成            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);            }        }    }}

 

 

 

 

 

 

 

 

 

 

 

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.