zoukankan      html  css  js  c++  java
  • 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指向的当前类。

  • 相关阅读:
    155. 最小栈
    160. 相交链表
    PAT 1057 Stack
    PAT 1026 Table Tennis
    PAT 1017 Queueing at Bank
    PAT 1014 Waiting in Line
    PAT 1029 Median
    PAT 1016 Phone Bills
    PAT 1010 Radix
    PAT 1122 Hamiltonian Cycle
  • 原文地址:https://www.cnblogs.com/xiaolaodi1999/p/15021075.html
Copyright © 2011-2022 走看看