![]() |
Creating a Java Thread by implementing Runnable Interface
We can create a thread in Java by extending Thread Class. A better way to create a thread in Java is to implement Runnable interface. A thread can be created by extending Java Thread class also. Now the question arises why implementing Runnable interface is a better approach? Answer is, if the thread class you are creating is to be subclass of some other class, it can’t extend from the Thread class. This is because Java does not allow a class to inherit from more than one class. In such a case one can use Runnable interface to implement threads.
Let us see an example of creating a thread by implementing Runnable interface. Code: Java
Code:
Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java JavaThe same program can be rewritten, by implementing Runnable interface, and creating a Thread object inside StringThread class rather than in the PrintString class as below. Code: Java
Code:
Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java |
Re: Creating a Java Thread by implementing Runnable Interface
Thank you for this thread. This sure seems simple enough. I have been trying to figure this out, and I can see from this thread that I was going about it in completely the wrong way. I think I got it now, thank goodness. I really appreciate all of the great information that I am finding in this forum.
|
Re: Creating a Java Thread by implementing Runnable Interface
Thanx for the script)) the code is admiring:)
|
Re: Creating a Java Thread by implementing Runnable Interface
Hi dude , your code is good and simple but I HAVE A QUESTION , will there be any difference if i call the StringThread.run method directly ???
ie Code: Java Code:
class PrintString |
Re: Creating a Java Thread by implementing Runnable Interface
start() method ll call run method... if do so (instead of start() , calling run()) here would be any Error or Exception run() method will simply be executed in the same Thread and new Thread will not be created.
and also u can't call same start() twice .... t. start ( ); t. start ( ); // IllegalThreadStateException............ Regards FOSS |
| All times are GMT +5.5. The time now is 07:57. |