Earlier we studied how to perform multithreading using the class Thread, but we know that in java multiple inheritance is not possible so if we want to perform multithreading in a derived class we would not be able to extend the Thread class. So to resolve this issue we can also perform multithreading by using interface!
The Runnable interface performs the same functions as that of the Thread class but we know that we can implement multiple interfaces together and even in a derived class, so they resolve this issue and so are generally preferred more.
Code:
Below is the code for the same.
The normal classes appear exactly same to that of implementing multithreading through Thread class. But the only difference lies in the object formation in the main class shown below.
We can see that first we need to make objects of the classes like we usually do but then we also need to make objects of the class Thread which would contain the objects m1 and m2 of the normal classes. And at the end we call t1 and t2 the objects of Thread class.
Output:
We can see how the statement of thread3 was executed before thread2 and that too the thread was switched before compelete execution as after printing the statement of thread3 6 times only instead of 50 times as mentioned in the code the statements of thread2 were printed.
Top comments (0)