Home  >  Core Java

Example of AtomicIntegerArray in Java

By Arvind Rai, December 25, 2012
1. AtomicIntegerArray belongs to the package java.util.concurrent.atomic.
2. java.util.concurrent.atomic is an array of integer.
3. AtomicIntegerArray is thread- safe. The values of AtomicIntegerArray can be modified automatically in multi threaded environment.
4. AtomicIntegerArray is available in java from jdk1.5.
package com.concretepage;

import java.util.concurrent.atomic.AtomicIntegerArray;

public class AtomicIntegerArrayTest {
	AtomicIntegerArray aia= new AtomicIntegerArray(10);
	class AddThread implements Runnable{

		@Override
		public void run() {
		//add the value 2 at index 1 
		aia.addAndGet(1,15);
		
		//at index 0, if current value is 15, then 5 is added to current value
		aia.compareAndSet(1,15,5);
		
			System.out.println(aia.get(1));
		}
		
	}
	
	class SubThread implements Runnable{

		@Override
		public void run() {
			
			//decrements by 1 from current value at index 1 
			aia.decrementAndGet(1);
			
			//weakly compare the first args to current value and sets
			aia.weakCompareAndSet(1,14,20);
			System.out.println(aia.get(1));
		}
		
	}
	
   public static void main(String... args){
	   new Thread(new AtomicIntegerArrayTest().new AddThread()).start();
	   new Thread(new AtomicIntegerArrayTest().new SubThread()).start();
   }
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us