2. Multi-threading in Java using Runnable

In previous chapter, we have seen how to use Thread (java.lang.Thread) class to create thread in Java language. In this chapter we will see how to use Runnable (java.lang.Runnable) Interface to create thread in Java language.

1. Runnable Interface

  1. Runnable interface is present in java.lang package.
  2. Only one method is declared inside Runnable interface.
  3. Method declaration: public void run();
  4. As Runnable is interface, we need help of Thread.start() method to start the thread, while creating Thread using Runnable interface. We will see how to do it.

2. Using Runnable Interface to create Thread.

Check program compilation and execution here! jDoodle

3. Two ways of Thread creation in Java.

Types of Thread creations in Java - Core Java Tutorial webencyclop.com

4. Different combinations of t.start() and t.run() methods.

Consider below program and let’s see the what each line does.

Case I (line 19): t1.start()

New Thread will be created, which is responsible for execution of run() method present in our MyRunnable class. This is usually the correct way to create Thread using Runnable interface.

Case II (line 20): t2.start()

New Thread will be created, which is responsible for execution of run() method present our Thread class. While creating t2 object we didn’t pass the target Runnable object, hence it called run() method from Thread class instead of run() method from our class.

Case III (line 22): t1.run()

New thread will not be created, but run() method will be called from MyRunnable class. (Only Thread.start() method is responsible for creating new Thread as we have seen in previous chapter.)

Case IV (line 23): t2.run()

New thread will not be created, but run() method will be called from Thread class. run() method in Thread class has blank implementation, so nothing will print when it executes. (Only Thread.start() method is responsible for creating new Thread as we have seen in previous chapter.)

Case V (line 25): r.start()

It will give Compile time error.
error: cannot find symbol | symbol: method start() | location: variable r of type MyRunnable | 1 error

Case V (line 26): r.run()

New Thread will not be created. But run() method present in Runnable class will be executed just like normal method call.

In second point, we have covered how to create Thread using Runnable interface, now let’s see which is better way to create the Thread and why? See you in next chapter.

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.