Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Would Like to Know the Difference ( Thread Specification )

 
JiaPei Jen
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a multithreading case. Suppose MyClass implements Runnable and
public static void main (String [] args) {
MyClass mc = new MyClass();
Case A:
new Thread(mc).start();
new Thread(mc).start();
Case B:
Thread t = new Thread(mc);
t.start();
t.start();
What is the difference do Case A and Case B make on the work that the threads are undertaking? I have run a test and seen some problem with Case B, however, I do not understand the output and do not have a transparent picture in my head about the difference. Please help.
 
David Harrigan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I know. Threads are difficult....however, the answer why (B) won't run is quite straight-forward. You see, you have created a new thread using the command:-
Thread t = new Thread(mc);
And then you have tried to run it twice using:-
t.start();
t.start();
The problem is that when the first command is executed (t.start() ) the likelihood is that it has started and it's off doing its merry thing...however, you now try to start the *same* thread again using the second command (t.start() ). Since this thread is already running then the JVM throws an IllegalMonitorExeception...you can't start a thread twice...you can pause it, cause it to wait for some event or whatever, but not start it twice (until that is that thread is dead and you want to perhaps start it again...).

In part (A). You are creating *two* threads and starting them off. This is fine, as they are independent of each other (however, they share the same instance members since the threads are creating from one instance of an object)...
Hope that helps...
[This message has been edited by David Harrigan (edited December 18, 2000).]
 
mohit joshi
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(until that is that thread is dead and you want to perhaps start it again...).


Once a thread is dead, invoking its start method will not make the thread run again, nor will it throw an exception in this case
 
JiaPei Jen
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, your explanation has really helped me. Thanks a lot.
 
Yes, my master! Here is the tiny ad you asked for:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!