Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How many threads are there?  RSS feed

 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just need to clarify my understanding regarding Threads and Stacks.

If we have this code snippet,
<blockquote>code:
<pre name="code" class="core"> public static void main (String [] args) {
...
method1();
method2();
method3();
method4();
myThread();
}
</pre>
</blockquote>

Assuming that all methodN (where N=1, 2, 3, 4) have only this code on its implementation: <blockquote>code:
<pre name="code" class="core">System.out.println("method 1/2/3/4");</pre>
</blockquote>

And myThread method,

<blockquote>code:
<pre name="code" class="core">void myThread() {
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
...
}
</pre>
</blockquote>

How many threads are there? I think there's two: the main thread and the myThread.

What about the methods? Are they also called thread? Or are they just part of the main thread? "part" = just included in the main's stack. The myThread on the other hand has its own stack. Hence it's thread #2.

Does it mean that one stack (series of stack frames/method calls) == one thread?

Thank you very much in advance.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, each thread has its own stack, and yes, one way to think of a thread is a continuous chain of method calls.

And yes, there are just two threads running the code shown here.

BUT...

If someone were to ask, "given this code, how many threads are running in the JVM", the answer is "we don't know, but almost certainly than two." Sun's JVMs create quite a few threads for their own uses: a garbage-collector thread, a finalizer thread, etc.
 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just ran a program that runs a thread separate from main, and watched the number of threads shown in Windows Task Manager. It showed that when I ran the program, altogether there were 11 extra threads. Two of them were my own (main, and MyThread), and the rest must have been for JVM purposes.
 
Dariusz Kordonski
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's for Windows only... As far as I remember, the JLS does not define any rules for JVM threads being in any way related to native OS threads.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!