简体   繁体   English

如果我的程序中有多个线程,从技术上讲每个线程是否都有自己的堆栈? 每个线程都有自己的堆吗?

[英]If I have multiple threads in my program, does each thread technically have it's own stack? Does each thread have it's own heap?

I have been trying to find the answer to this question in the API (and with Google) but I am not able to find anything that directly discusses the state of the call stack and heap in a multi-threaded program. 我一直在尝试在API (以及与Google)中找到此问题的答案,但是我找不到能够直接讨论多线程程序中调用堆栈和堆状态的任何内容。

Also, does a synchronised object get flip flopped between both stacks (assuming they are seperate stacks) 另外,同步对象是否在两个堆栈之间都被翻转了(假设它们是单独的堆栈)

They share the heap, but each thread has its own stack (otherwise it wouldn't know what it's executing). 它们共享堆,但是每个线程都有自己的堆栈(否则它将不知道它在执行什么)。

Nothing is flip flopped (I don't understand why you think that would happen). 什么都不会失败(我不明白你为什么认为会发生这种情况)。 Objects can't be synchronized, only code is synchronized (by acquiring an object's monitor or lock). 无法同步对象,只能同步代码(通过获取对象的监视器或锁)。

Multiple threads in Java share the same heap space. Java中的多个线程共享相同的堆空间。 Each thread gets its own stack. 每个线程都有自己的堆栈。

The Java Virtual Machine is stacked based. Java虚拟机是基于堆栈的。 In pseudocode an add instruction may look like this. 在伪代码中,添加指令可能如下所示。

push 2 //Stack: 2
push 3 //Stack: 2,3
add    //Stack: 5

If threads shared the same address space then it may turn into something weird since they share the same stack. 如果线程共享相同的地址空间,则由于它们共享相同的堆栈,因此可能会变得很奇怪。 When they start popping off values from other threads the virtual machine will do strange things and may crash. 当它们开始从其他线程弹出值时,虚拟机将执行奇怪的操作并可能崩溃。

Here is what it might look like if we did that same example above on two threads.(This is just a possible way the stack might look like.) 如果我们在两个线程上执行了相同的示例,则可能是这样的(这只是堆栈可能的样子)。

Thread 1               Thread 2
push 2 //Stack: 2    : push 2 //Stack: 2,2
push 3 //Stack: 2,2,3: push 3 //Stack: 2,2,3,3
add //Stack 2,2,6    : add //Stack 2,8

You can easily see that if they shared the same stack, things would get corrupt fast. 您可以轻松地看到,如果他们共享相同的堆栈,事情将会很快被破坏。

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

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