Java Lambda表达式中的this

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指向的当前类。

posted @ 2021-07-16 17:15  小老弟1999  阅读(867)  评论(0编辑  收藏  举报