Java 5 Application of the original sub-operation class, Java 5 atomic type
The java. util. concurrent. atomic package provides operations for basic data types, basic data types in arrays, and basic data types in classes. For more information, see API.
The following example briefly introduces the use of the AtomicInteger class:
1 public class AtomicTest { 2 public static void main(String[] args) { 3 final Ticket ticket = new Ticket(); 4 for (int i = 0; i < 3; i++) { 5 new Thread(new Runnable() { 6 @Override 7 public void run() { 8 while(ticket.getCount()>0){ 9 System.out.println(Thread.currentThread().getName()+" count: "+ticket.decrement());10 }11 }12 }).start();13 }14 15 }16 }17 class Ticket{18 public AtomicInteger count = new AtomicInteger(100);19 20 public int decrement(){21 return count.getAndDecrement();22 }23 24 public int getCount() {25 return count.get();26 }27 28 }
AtomicIntegerArray and AtomicIntegerFieldUpdater also provide similar operations, except that AtomicIntegerArray is for the basic types in the array, while AtomicIntegerFieldUpdater is for the basic types in specific objects.