Advertisement
Guest User

Untitled

a guest
Jan 24th, 2014
623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3.  
  4. public class ThreadSafeIntegerIncrementTestClass
  5. {
  6.     volatile static int simpleInt = 0;
  7.     static AtomicInteger atomicInteger = new AtomicInteger(0);
  8.     static int synchronizedGetterInteger = 0;
  9.    
  10.     public synchronized static void syncronizedIncrementer()
  11.     {
  12.         synchronizedGetterInteger++;
  13.     }
  14.    
  15.     public static void main(final String... args) throws InterruptedException
  16.     {
  17.         class IncrementerThread extends Thread implements Runnable
  18.         {
  19.             @Override
  20.             public void run()
  21.             {
  22.                 for(int i = 0 ; i<1000; i++)
  23.                 {
  24.                     ThreadSafeIntegerIncrementTestClass.simpleInt++;
  25.                     ThreadSafeIntegerIncrementTestClass.atomicInteger.incrementAndGet();
  26.                     ThreadSafeIntegerIncrementTestClass.syncronizedIncrementer();
  27.                 }
  28.             }
  29.         }
  30.        
  31.         final ArrayList<IncrementerThread> threadList = new ArrayList<IncrementerThread>();
  32.        
  33.         for(int i = 0; i<1000; i++)
  34.             threadList.add(new IncrementerThread());
  35.         for(final IncrementerThread currentThread : threadList)
  36.             currentThread.start();
  37.         for(final IncrementerThread currentThread : threadList)
  38.             currentThread.join();
  39.        
  40.         System.out.println(simpleInt);
  41.         System.out.println(atomicInteger);
  42.         System.out.println(synchronizedGetterInteger);
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement