1 import java.text.DateFormat; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 5 public class OrderNo{ 6 private static int sn = 0; 7 8 public static String NextOrderNo(){ 9 if(sn == 999999999) 10 sn = 0; 11 else 12 sn++; 13 DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 14 return df.format(new Date()) + padRight(String.valueOf(sn),9, '0'); 15 } 16 public static String padLeft(String src, int len, char ch) { 17 int diff = len - src.length(); 18 if (diff <= 0) { 19 return src; 20 } 21 22 char[] charr = new char[len]; 23 System.arraycopy(src.toCharArray(), 0, charr, 0, src.length()); 24 for (int i = src.length(); i < len; i++) { 25 charr[i] = ch; 26 } 27 return new String(charr); 28 } 29 public static String padRight(String src, int len, char ch) { 30 int diff = len - src.length(); 31 if (diff <= 0) { 32 return src; 33 } 34 35 char[] charr = new char[len]; 36 System.arraycopy(src.toCharArray(), 0, charr, diff, src.length()); 37 for (int i = 0; i < diff; i++) { 38 charr[i] = ch; 39 } 40 return new String(charr); 41 } 42 // 防止创建类的实例 43 private OrderNo(){} 44 45 public static void main(String[] args) { 46 Thread t1 = new Thread(){ 47 @Override 48 public void run() { 49 for (int i = 0; i < 5000; i++) { 50 try { 51 sleep(300); 52 System.out.println(OrderNo.NextOrderNo()); 53 } catch (InterruptedException e) { 54 e.printStackTrace(); 55 } 56 } 57 } 58 }; 59 Thread t2 = new Thread(){ 60 @Override 61 public void run() { 62 for (int i = 0; i < 5000; i++) { 63 try { 64 sleep(200); 65 System.out.println(OrderNo.NextOrderNo()); 66 } catch (InterruptedException e) { 67 e.printStackTrace(); 68 } 69 } 70 } 71 }; 72 Thread t3 = new Thread(){ 73 @Override 74 public void run() { 75 for (int i = 0; i < 5000; i++) { 76 try { 77 sleep(50); 78 System.out.println(OrderNo.NextOrderNo()); 79 } catch (InterruptedException e) { 80 e.printStackTrace(); 81 } 82 } 83 } 84 }; 85 t1.run(); 86 t2.run(); 87 t3.run(); 88 } 89 } 90