1、問題:為什么 testVO方法能夠通過鎖解決原子性問題,testVo1方法不能夠通過鎖解決原子性問題?
public class TestVolatile {
private volatile int num = 0;
private int count = 0;//完成線程累加
private final int THREAD_COUNT = 20;//線程數目
public void textVo() {
//開啟20個線程
for (int x = 0; x < THREAD_COUNT; x++) {
Thread thread= new Thread(()-> {
for (int i = 0; i < 1000; i++) {
synchronized (this) {
num++;
}
}
threadOK();
});
thread.start();
}
}
public void testVo1(){
//開啟20個線程
for (int x = 0; x < THREAD_COUNT; x++) {
Thread thread= new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
synchronized (this) {
num++;
}
}
threadOK();
}
});
thread.start();
}
}
private void threadOK() {
count++;
//等待所有線程都執行完累加
if (count == THREAD_COUNT) {
System.out.println(num);
}
}
public static void main(String[] args) {
new TestVolatile().testVo1();
//new TestVolatile().textVo();
}
}
2、猜測:加鎖的對象不一樣!
3、驗證
4、原因
lambda表達式最終會返回一個實現了指定接口的實例,看上去和內部匿名類很像,但有一個最大的區別就是代碼里面的this,內部匿名類this指向的就是匿名類,而lambda表達式里面的this指向的當前類。