code_junkie

When would you call java's thread.run() instead of thread.start()?

Nov 12th, 2011
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. /*
  2. By calling t1.start(),
  3. we are getting the main calling thread returned immediately
  4. after the t1.start() called and is ready to proceed for other
  5. operations.And the thread t1 starts executing the run method of the object r.
  6. Hence the the output will be:
  7.  
  8. I am the main thread , i created thread t1 and had it execute run method, which is currently looping from 0 to 1000000
  9.  
  10. I am done executing run method of testThread
  11.  
  12. */
  13.  
  14.  
  15. /* If we call t1.run() instead of t1.start(), (just replace t1.start() with t1.run() in the code for testing)
  16. its like a regular method call and the main thread will not return until the run method completes,
  17. hence the output will be:
  18.  
  19. I am done executing run method of testThread
  20.  
  21. I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000
  22.  
  23. */
  24.  
  25.  
  26. class testThread implements Runnable{
  27.  
  28. public void run()
  29. {
  30. for(int i=0;i<1000000;i++){} //a simple delay block to clarify.
  31.  
  32. System.out.println("I am done executing run method of testThread");
  33.  
  34. }
  35. }
  36.  
  37. public class mainClass{
  38.  
  39. public static void main(String [] args)
  40. {
  41. testThread r = new testThread();
  42. Thread t1 = new Thread(r);
  43. t1.start(); /* Question is: can we call instead t1.run() */
  44. System.out.println("I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000");
  45.  
  46. }
  47. }
  48.  
  49. public synchronized void start() {
  50. /**
  51. * This method is not invoked for the main method thread or "system"
  52. * group threads created/set up by the VM. Any new functionality added
  53. * to this method in the future may have to also be added to the VM.
  54. *
  55. * A zero status value corresponds to state "NEW".
  56. */
  57. if (threadStatus != 0)
  58. throw new IllegalThreadStateException();
  59. group.add(this);
  60. start0();
  61. if (stopBeforeStart) {
  62. stop0(throwableFromStop);
  63. }
  64. }
  65.  
  66. private native void start0();
Add Comment
Please, Sign In to add comment