Wednesday, 8 June 2016

Calling run method directly of thread (created by implementing Runnable interface) in Java

It will works as ordinary java method because the thread class run() method implementation.

voidjava.lang.Thread.run()

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns. Subclasses of Thread should override this method.

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

Here target is our runnable class which will set while calling Thread class constructor while creating thread.

Example:

class MyThread implements Runnable {
     @Override
     public void run() {
           System.out.println("This is my thread !!");
     }
}

public class ThreadTest {
     public static voidmain(String[] args) {
           MyThread  myThread = new MyThread();
          
           Thread thread = new Thread(myThread);
          
           thread.run();
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...