Saturday 29 June 2019

Defining a Thread by implementing Runnable interface

  • We can define a Thread even by implementing Runnable interface also.

  • Runnable interface present in java.lang.pkg and contains only one method run().
Example:

class ThreadDemo
{
              public static void main(String[] args)
              {
                             MyRunnable r=new MyRunnable();
                             Thread t=new Thread(r);//here r is a Target Runnable
                             t.start();

                             for(int i=0;i<10;i++)
                             {
                                           System.out.println("main thread");
                             }
              }
}


Output:
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
  • We can't expect exact output but there are several possible outputs.
Case study:
MyRunnable r = new MyRunnable();
Thread t1 = new  Thread();
Thread t2 = new Thread(r);

Case-1 : t1.start()
  • A new Thread will be created which is responsible for the execution of Thread class run()method.
Output:
main thread
main thread
main thread
main thread
main thread

Case 2: t1.run():
  • No new Thread will be created but Thread class run() method will be executed just like a normal method call.
Output:
main thread
main thread
main thread
main thread
main thread

Case 3: t2.start():
  • New Thread will be created which is responsible for the execution of MyRunnable run() method.
Output:
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread

Case 4: t2.run():
  • No new Thread will be created and MyRunnable run() method will be executed just like a normal method call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread

Case 5: r.start():
  • We will get compile time error saying start()method is not available in MyRunnable class.
Output:
Compile time error D:\test>javac ThreadDemo.java
ThreadDemo.java:18: cannot find symbol Symbol: method start()
Location: class MyRunnable

Case 6: r.run():
  • No new Thread will be created and MyRunnable class run() method will be executed just like a normal method call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread



Thanks..!!

No comments:

Post a Comment