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

  • 相关阅读:
    Python基础
    thinkphp中session跨域问题
    thinkphp实现短信验证注册
    微信公众号支付流程(Node实现)
    支付宝手机网站支付流程(Node实现)
    浏览器打开URL的方式
    Jmeter取样器之Java Request
    获取Tomcat更详细的日志
    使用PowerDesigner转换不同数据库的表结构
    NameValuePair在API22过时问题
  • 原文地址:https://www.cnblogs.com/xiaolaodi1999/p/15021075.html
Copyright © 2011-2022 走看看