Java AtomicIntegerArray class
import java.util.concurrent.atomic.AtomicIntegerArray; class Producer implements Runnable { private AtomicIntegerArray vector; public Producer(AtomicIntegerArray vector) { this.vector = vector; }//from w w w . j a v a2 s .co m @Override public void run() { for (int i = 0; i < vector.length(); i++) { vector.getAndIncrement(i); } } } class Consumer implements Runnable { private AtomicIntegerArray vector; public Consumer(AtomicIntegerArray vector) { this.vector = vector; } @Override public void run() { for (int i = 0; i < vector.length(); i++) { vector.getAndDecrement(i); } } } public class Main { public static void main(String[] args) { int Count = 100; AtomicIntegerArray vector = new AtomicIntegerArray(1000); Producer incrementer = new Producer(vector); Consumer decrementer = new Consumer(vector); Thread threadIncrementer[] = new Thread[Count]; Thread threadDecrementer[] = new Thread[Count]; for (int i = 0; i < Count; i++) { threadIncrementer[i] = new Thread(incrementer); threadDecrementer[i] = new Thread(decrementer); threadIncrementer[i].start(); threadDecrementer[i].start(); } for (int i = 0; i < Count; i++) { try { threadIncrementer[i].join(); threadDecrementer[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < vector.length(); i++) { if (vector.get(i) != 0) { System.out.println("Vector[" + i + "] : " + vector.get(i)); } } } }