加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java:多线程访问主线程变量/方法

发布时间:2020-12-15 04:14:01 所属栏目:Java 来源:网络整理
导读:我正在测试以下代码,我想知道线程如何访问增量方法? 我在想这个,因为thread1和thread2是从匿名类创建的对象,它们不继承worker类,它们如何访问increment()方法?它背后的理论是什么? public class Worker { private int count = 0; public synchronized voi
我正在测试以下代码,我想知道线程如何访问增量方法?

我在想这个,因为thread1和thread2是从匿名类创建的对象,它们不继承worker类,它们如何访问increment()方法?它背后的理论是什么?

public class Worker {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public void run() {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                for(int i = 0; i < 10000; i++) {
                    increment();
                }
            }
        });
        thread1.start();

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                for(int i = 0; i < 10000; i++) {
                    increment();
                }
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Count is: " + count);
    }
}

解决方法

Java语言规范(JLS)声明这个约为 Inner Classes and Enclosing Instances

Inner classes include local (§14.3),anonymous (§15.9.5) and
non-static member classes (§8.5).

和about Inner Classes and Enclosing Instances

An inner class C is a direct inner class of a class O if O is the
immediately lexically enclosing class of C and the declaration of C
does not occur in a static context.

最后是about Qualified this

Any lexically enclosing instance (§8.1.3) can be referred to by
explicitly qualifying the keyword this.

Let C be the class denoted by ClassName. Let n be an integer such that
C is the n’th lexically enclosing class of the class in which the
qualified this expression appears.

The value of an expression of the form ClassName.this is the n’th
lexically enclosing instance of this.

这就是为什么你可以访问工人的成员.

电话

new Runnable()

在Worker实例方法中,为Worker创建一个内部类.因此,工人是Runnable的第0个词汇封闭类.关于上面的JLS引号,将ClassName替换为Worker,您可以访问您的方法

Worker.this.increment()

这是由编译器隐式完成的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读