[JAVA concurrent programming practice] 10. concurrent program testing and java practice
1. Generate a random number
Package cn. study. concurrency. ch12; public class Util {public static int xorShift (int y) {// shift left and unsigned right, and last XOR operation (XOR, if the two bits are different, the value is 1; otherwise, the value is 0) y ^ = (y <6); y ^ = (y >>> 21 ); y ^ = (y <7); return y; // The initial value of y is Random Seed} public static void main (String [] args) {for (int I = 0; I <10; ++ I) {System. out. println (xorShift (int) System. nanoTime ()));}}}
2. cache queue
Package cn. study. concurrency. ch12; import java. util. concurrent. semaphore; public class BoundedBuffer <E >{// semaphores private final Semaphore availableItems, availableSpaces; private final E [] items; private int putPosition = 0, takePosition = 0; public BoundedBuffer (int capacity) {availableItems = new Semaphore (0); availableSpaces = new Semaphore (capacity); items = (E []) new Object [capacity];} public boolea N isEmpty () {// This indicates that return availableItems is empty. availablePermits () = 0;} public boolean isFull () {// indicates that the queue is full. return availableSpaces. availablePermits () = 0;} // put an object, first request a semaphore from availableSpaces, and then return an availableItems signal public void put (E x) throws InterruptedException {// reduce a license availableSpaces. acquire (); doInsert (x); // Add a license availableItems. release ();} // release a Data Object public E take () throws Int ErruptedException {// when an object is released, remove a connection license availableItems. acquire (); E item = doExtract (); availableSpaces. release (); // after the data is retrieved, a return item may be inserted.} private synchronized void doInsert (E x) {int I = putPosition; items [I] = x; putPosition = (++ I = items. length )? 0: I;} // whether it is data retrieval or data retrieval, the private synchronized E doExtract () {int I = takePosition; E x = items [I] is obtained cyclically. items [I] = null; takePosition = (++ I = items. length )? 0: I; return x;} public static void main (String [] args) throws InterruptedException {BoundedBuffer <Integer> bb = new BoundedBuffer <Integer> (10); bb. take (); if (bb. isEmpty () {System. out. println ("null");} if (bb. isFull () {System. out. println ("full ");}}}
3. Test Method
Package cn. study. concurrency. ch12; import java. util. concurrent. cyclicBarrier; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. atomic. atomicInteger; public class PutTakeTest {// create a thread pool private static final ExecutorService pool = Executors. newCachedThreadPool (); // atomic int data, which is used to calculate whether the thread design is reasonable and whether the thread security is private final AtomicInteger putSum = new AtomicI Nteger (0); private final AtomicInteger takeSum = new AtomicInteger (0); private final partition icbarrier barrier; // barrier private final BoundedBuffer <Integer> bb; // queue private final int nTrials, nPairs; // Number of queues to be created and barrier points to be created // constructor public PutTakeTest (int capacity, int npairs, int ntrials) {this. bb = new BoundedBuffer <Integer> (capacity); this. nTrials = ntrials; this. nPairs = npairs; // + 1 is for encoding after all threads are established. Determines when to start all threads. barrier = new CyclicBarrier (2 * npairs + 1);} // Producer Thread class Producer implements Runnable {@ Override public void run () {try {// design Random Seed, exclusive or operation int seed = (this. hashCode () ^ (int) System. nanoTime (); int sum = 0; barrier. await (); // run the barrier wait for (int I = nTrials; I> 0; -- I) {bb. put (seed); sum + = seed; seed = Util. xorShift (seed); // obtain the random value} // obtain the value and add it to putsum. getAndAdd (sum); barri Er. await (); // Add a fence to mark the end of running} catch (Exception e) {System. out. println ("???? Producer ") ;}}// Consumer Thread class Consumer implements Runnable {@ Override public void run () {try {barrier. await (); // wait for int sum = 0; for (int I = nTrials; I> 0; -- I) {sum + = bb. take ();} // obtain the value and add it to the putsum takeSum. getAndAdd (sum); barrier. await (); // Add a fence to mark the end of running} catch (Exception e) {e. printStackTrace (); System. out. println (Thread. currentThread (). getName () + "???? Consumer ") ;}}// test function public void test () {try {for (int I = 0; I <nPairs; ++ I) {pool.exe cute (new Producer (); pool.exe cute (new Consumer ();} // when all fields are added, open the barrier. await (); // The 2n + 1 // After the thread is executed, await is called after each thread is executed. After all the threads are executed, barrier is called. await (); // determine whether the result is equal to if (putSum. get () = takeSum. get () {System. out. println ("the program is OK");} else {System. out. println ("program security vulnerabilities") ;}} catch (Exception e ){ System. out. println ("???? Test ") ;}} public static void main (String [] args) {// The queue capacity is 10, and each thread starts with 10, with a total of 100000 data records new PutTakeTest (10, 2,100 ). test (); pool. shutdown (); // end thread after execution }}