概述:
? ? ?关于并发场景下的乐观锁,参考网上的例子写了一个demo,效果出来了,但是引出一个新的问题,锁的对象本质到底是什么?
? ? ? ?之前的理解是锁方法即只有一个线程可以进入此方法,锁对象即只有一个对象能修改此对象的状态;get方法是一个只读的方法,上不上锁应该没有影响才对,点解?
?
public class SimulatedCAS {
??? private int value;
??? public SimulatedCAS(int value) {
??????? this.value = value;
??? }
??? /** 此处上锁成功率要高很多,原因不清楚,讲道理,锁应该是锁的方法,不是value呀 */
??? public synchronized int get(){
??????? return value;
??? }
??? public synchronized boolean casAdd(int expectedValue, int newValue){
??? try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
??????? if(this.value == expectedValue){//如果期望值与当前V位置的值相同就给予新值
??????????? value = newValue;
??????????? return true;
??????? }
??????? return false;//返回V位置原有的值
??? }
??? public static void main(String[] args) throws Exception {
??????? SimulatedCAS casObj = new SimulatedCAS(10);
???????
??????? Runnable r = new Runnable() {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
long currentTimeMillis = System.currentTimeMillis();
Random rand = new Random();
int nextInt = rand.nextInt(10) + 1;
boolean succ = false;
do {
int oldValue = casObj.get();
int newValue = oldValue+nextInt;
succ = casObj.casAdd(oldValue, newValue);
int resultValue = casObj.get();
System.out.println(currentTimeMillis + "#" + threadName + "#" + oldValue + "~" + newValue);
System.out.println("\t随机数:" + nextInt + "\t操作结果:" + succ
+ "\t 操作:" + oldValue + " + " + nextInt + " = " + resultValue);
} while(!succ);
}
};
???????
???????
List<Thread> tList = new ArrayList<>();
??????? for (int i = 0; i < 6; i++) {
??????? Thread t = new Thread(r);
??????? t.setName("thread" + i);
???????
??????? tList.add(t);
???????
??????? t.start();
??????? }
???????
??????? for (Thread thread : tList) {
??????????? thread.join();
??????? }
???????
??????? System.out.println("result: " + casObj.get());
???????
??? }
}
?