1.对象锁
package com.peopleyun.lock;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by Administrator on 2018/1/3.
*/
public class ObjectLock {
public static int num = 0;
static ExecutorService executorService = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
final OrderLock orderLock = new OrderLock();
executorService.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000 ; i ++ ){
System.out.println(Thread.currentThread().getName() + " " + orderLock.setInCrease());
}
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000 ; i ++ ){
System.out.println(Thread.currentThread().getName() + " " + orderLock.setInCrease());
}
}
});
try {
executorService.shutdown();
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(num);
}
static class OrderLock{
public synchronized String setInCrease(){
num ++;
return getStringDateShort() + num; //返回订单ID
}
}
public static String getStringDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
}
2.类锁生成唯一性ID
package com.peopleyun.lock;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeU