Monday 19 September 2011

Create New Thread Using Runnable Example

  1. /*
  2. Create New Thread Using Runnable Example
  3. This Java example shows how to create a new thread by implementing
  4. Java Runnable interface.
  5. */
  6.  
  7. /*
  8.  * To create a thread using Runnable, a class must implement
  9.  * Java Runnable interface.
  10.  */
  11. public class CreateThreadRunnableExample implements Runnable{
  12.  
  13. /*
  14. * A class must implement run method to implement Runnable
  15. * interface. Signature of the run method is,
  16. *
  17. * public void run()
  18. *
  19. * Code written inside run method will constite a new thread.
  20. * New thread will end when run method returns.
  21. */
  22. public void run(){
  23.  
  24. for(int i=0; i < 5; i++){
  25. System.out.println("Child Thread : " + i);
  26.  
  27. try{
  28. Thread.sleep(50);
  29. }
  30. catch(InterruptedException ie){
  31. System.out.println("Child thread interrupted! " + ie);
  32. }
  33. }
  34.  
  35. System.out.println("Child thread finished!");
  36. }
  37.  
  38. public static void main(String[] args) {
  39.  
  40. /*
  41. * To create new thread, use
  42. * Thread(Runnable thread, String threadName)
  43. * constructor.
  44. *
  45. */
  46.  
  47. Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
  48.  
  49. /*
  50. * To start a particular thread, use
  51. * void start() method of Thread class.
  52. *
  53. * Please note that, after creation of a thread it will not start
  54. * running until we call start method.
  55. */
  56.  
  57. t.start();
  58.  
  59. for(int i=0; i < 5; i++){
  60.  
  61. System.out.println("Main thread : " + i);
  62.  
  63. try{
  64. Thread.sleep(100);
  65. }
  66. catch(InterruptedException ie){
  67. System.out.println("Child thread interrupted! " + ie);
  68. }
  69. }
  70. System.out.println("Main thread finished!");
  71. }
  72. }
  73.  
  74. /*
  75. Typical output of this thread example would be
  76.  
  77. Main thread : 0
  78. Child Thread : 0
  79. Child Thread : 1
  80. Main thread : 1
  81. Main thread : 2
  82. Child Thread : 2
  83. Child Thread : 3
  84. Main thread : 3
  85. Main thread : 4
  86. Child Thread : 4
  87. Child thread finished!
  88. Main thread finished!
  89.  
  90. */

No comments:

Post a Comment

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com