Multithreaded AtomicInteger

 

public class AtomicIntegerTest {
 //Atomic operation: use AtomicInteger to increment and decrement to achieve synchronization
 private AtomicInteger num = new AtomicInteger(0);

 public static void main(String[] args) throws InterruptedException {
  AtomicIntegerTest a = new AtomicIntegerTest();
  
  for(int i=0;i<50;i++) {
   a.newThread();
  }
  System.out.println(a.num.get());
 }
 
 void newThread() throws InterruptedException{
  Thread t = new Thread(new T());
  t.start();
  t.join();
 }

 class T implements Runnable{

  public void run() {
   //int i = num.incrementAndGet(); //++i
   int i = num.decrementAndGet(); //--i
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

public class AtomicLongTest {
 //Atomic operation: use AtomicLong to increment and decrement to achieve synchronization
 private AtomicLong num = new AtomicLong(0);

 public static void main(String[] args) throws InterruptedException {
  AtomicLongTest a = new AtomicLongTest();
  
  for(int i=0;i<50;i++) {
   a.newThread();
  }
//  System.out.println(a.num.get());
 }
 
 void newThread() throws InterruptedException{
  Thread t = new Thread(new T());
  t.start();
//  t.join();
 }

 class T implements Runnable{

  public void run() {
   long i = num.incrementAndGet(); //++i
   //long i = num.decrementAndGet(); //--i
   System.out.println(i);
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326037630&siteId=291194637