Guest User

Untitled

a guest
Jan 11th, 2011
265
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.concurrent.atomic.AtomicInteger;
  2.  
  3. public class AtomicTest {
  4.     private AtomicInteger currentId = new AtomicInteger();
  5.     private static final int MAX_ID = 1;
  6.  
  7.     public int getNextId() {
  8.         for (;;) {
  9.             int current = currentId.get();
  10.             int next = current + 1;
  11.             if (next>MAX_ID) {
  12.                 next = 0;
  13.             }
  14.             if (currentId.compareAndSet(current, next)) {
  15.                 return next;
  16.             }
  17.         }
  18.     }
  19.  
  20.     public static void main(String[] args) throws InterruptedException {
  21.         final AtomicTest test = new AtomicTest();
  22.  
  23.         final AtomicInteger count0 = new AtomicInteger();
  24.         final AtomicInteger count1 = new AtomicInteger();
  25.  
  26.  
  27.         for (int i=0; i<20; i++) {
  28.             new Thread(new Runnable() {
  29.                 @Override
  30.                 public void run() {
  31.                     while (!Thread.currentThread().isInterrupted()) {
  32.                         int x = test.getNextId();
  33.                         if (x==0) {
  34.                             count0.incrementAndGet();
  35.                         } else {
  36.                             count1.incrementAndGet();
  37.                         }
  38.                     }
  39.                 }
  40.             }).start();
  41.         }
  42.  
  43.         for (;;) {
  44.             int x0 = count0.get();
  45.             int x1 = count1.get();
  46.             double r = (double)x0/(double)x1;
  47.             System.out.println("0 " + x0 + " 1 " + x1 + " r " + r);
  48.             Thread.sleep(1000);
  49.         }
  50.     }
  51.  
  52. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×