问题描述
在思考 Java/C# 编程时,我想知道属于对象的方法如何在内存中表示,以及这个事实如何与多线程有关.
While thinking a little bit about programming in Java/C# I wondered about how methods which belong to objects are represented in memory and how this fact does concern multi threading.
- 是为内存中的每个对象单独实例化的方法还是做同一类型的所有对象共享该方法的一个实例?
- 如果是后者,执行线程如何知道哪个对象的要使用的属性?
- 是否可以修改方法的代码C# 反射一个,多个对象中只有一个对象同类型?
- 不使用类属性的静态方法是否总是线程安全的?
我试图对这些问题下定决心,但我不确定他们的答案.
I tried to make up my mind about these questions, but I'm very unsure about their answers.
推荐答案
源代码中的每个方法(在 Java、C#、C++、Pascal 中,我认为每个 OO 和过程语言...)只有一个 在二进制文件和内存中复制.
Each method in your source code (in Java, C#, C++, Pascal, I think every OO and procedural language...) has only one copy in binaries and in memory.
一个对象的多个实例具有不同的字段,但都共享相同的方法代码.从技术上讲,有一个过程采用隐藏的 this
参数来提供在对象上执行方法的错觉.实际上,您正在调用一个过程并将结构(一袋字段)与其他参数一起传递给它.这是一个简单的 Java 对象和或多或少等效的伪 C 代码:
Multiple instances of one object have separate fields but all share the same method code. Technically there is a procedure that takes a hidden this
parameter to provide an illusion of executing a method on an object. In reality you are calling a procedure and passing structure (a bag of fields) to it along with other parameters. Here is a simple Java object and more-or-less equivalent pseudo-C code:
class Foo {
private int x;
int mulBy(int y) {
return x * y
}
}
Foo foo = new Foo()
foo.mulBy(3)
被翻译成这个伪C代码(封装是由编译器和运行时/VM强制的):
is translated to this pseude-C code (the encapsulation is forced by the compiler and runtime/VM):
struct Foo {
int x = 0;
}
int Foo_mulBy(Foo *this, int y) {
return this->x * y;
}
Foo* foo = new Foo();
Foo_mulBy(foo, 3)
您必须区分代码和局部变量以及它操作的参数(数据).数据存储在调用堆栈中,每个线程都是本地的.代码可以由多个线程执行,每个线程都有自己的指令指针副本(放置在它当前执行的方法中).也因为 this
是一个参数,它是线程本地的,所以每个线程可以同时操作不同的对象,即使它运行相同的代码.
You have to draw a difference between code and local variables and parameters it operates on (the data). Data is stored on call stack, local to each thread. Code can be executed by multiple threads, each thread has its own copy of instruction pointer (place in the method it currently executes). Also because this
is a parameter, it is thread-local, so each thread can operate on a different object concurrently, even though it runs the same code.
话虽如此,您不能只修改一个实例的方法,因为方法代码在所有实例之间共享.
That being said you cannot modify a method of only one instance because the method code is shared among all instances.
这篇关于内存中的方法表示是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!