Java AtomicLong generate id for threads

Description

Java AtomicLong generate id for threads

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

public class Main {
   AtomicLong orderIdGenerator = new AtomicLong(0);
   List<Order> orders = Collections.synchronizedList(new ArrayList<Order>());

   public static void main(String[] args) {
      new Main().start();
   }//from  w  w w. j av  a 2s .  c o  m

   private void start() {
      for (int i = 0; i < 10; i++) {
         Thread orderCreationThread = new Thread(new Runnable() {
            public void run() {
               for (int i = 0; i < 10; i++) {
                  createOrder();
               }
            }
         });
         orderCreationThread.setName("Order Creation Thread " + i);
         orderCreationThread.start();
      }

      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

      Set<Long> orderIds = new HashSet<Long>();
      for (Order order : orders) {
         if (orderIds.contains(order.getOrderId())) {
            System.out.println("The horror! an orderID has been reused!");
         }
         orderIds.add(order.getOrderId());
         System.out.println("Order id:" + order.getOrderId());
      }
   }

   private void createOrder() {
      long orderId = orderIdGenerator.incrementAndGet();
      Order order = new Order( orderId);
      orders.add(order);
   }

}

class Order {
   long orderId;

   Order( long orderId) {
      this.orderId = orderId;
   }

   public long getOrderId() {
      return orderId;
   }
}



PreviousNext

Related