简体   繁体   English

这两个Java之间的区别(创建对象)

[英]Difference between these two Java (Creating objects)

I'm learning about threads in Java, and I've come across these two: 我正在学习Java中的线程,并且遇到了以下两个问题:

Class Runner implements runnable and is passed onto the constructor in the Thread object 类运行器实现可运行,并传递到Thread对象的构造函数中

  1. Runner runner = new Runner();
    Thread thread1 = new Thread(runner);

  2. Thread thread1 = new Thread(new Runner());

I've never encountered the second option. 我从未遇到过第二种选择。 It would be great if someone could help a beginner Java programmer out and tell me what the use is for the second variation, and what it is actually called when you create an instance of a class inside the constructor? 如果有人可以帮助新手Java程序员并告诉我第二个变体的用途是什么,以及在构造函数内部创建类的实例时实际调用了什么,那将是很好的选择?

Thank you. 谢谢。

There is no difference except after the first one, you have a variable runner that refers to the Runner , and after the second one, you don't. 目前除了第一个之后,你有一个变量没有区别runner是指Runner ,并在第二个之后,你不知道。 But both of them create a new Runner object, and construct a new Thread using that new object. 但是他们两个都创建了一个新的Runner对象,并使用该新对象构造了一个新的Thread

This is just the ability to use any expression as an object, whether a variable, or constructor. 这仅仅是将任何表达式用作对象的能力,无论是变量还是构造函数。

As an analogy, the first is like "Grow an apple and put it on the table. Then, make a pie from that apple on the table" 打个比方,第一个就像“种一个苹果然后放在桌子上。然后,用那个苹果在桌子上做馅饼”

The second is akin to "Grow an apple and make a pie out of it". 第二个类似于“种一个苹果,然后做成一个馅饼”。 It simply avoid an intermediate variable to hold the apple (in the code, a runnable) 它只是避免使用中间变量来保存苹果(在代码中为可运行的)

If you needed to do something to the apple other than to pass it, you'd need to (in most cases) store to an intermediate variable. 如果您需要对苹果做些其他事情而不是传递它,则需要(在大多数情况下)存储到中间变量。 The analogy here is "Grow the apple, put it on the table. Peel the apple. Make a new pie using the apple" 这里的类比是“种苹果,放在桌子上。去皮。用苹果做一个新馅饼”

I am giving takeaways first 我先给外卖

They both are same and JIT will optimize the first version into second 两者相同, JIT会将第一个版本优化为第二个版本

One main difference though. 尽管有一个主要区别。 If you ever want to call some function of runner you can do so at the first version, but you can't at the second one. 如果你想调用的一些功能, runner则可以在第一个版本做到这一点,但你不能在第二个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM