There are 2 ways :
- By extending a Thread class
- By implementing runnable interface.
Defining Thread:
- Extending Thread class
- Overriding run() method
Example:
public class MyThread extends Thread{ public void run(){ System.out.println("Important job goes here.."); } public static void main(String[] args){ MyThread mt = new MyThread(); mt.start(); } }
Output: Important job goes here..
If you implement Runnable, instantiation is only slightly
less simple. To have code run by a separate thread, you still need a Thread
instance. But rather than combining both the thread and the job (the code in
the run()method) into one class, you've split it into two classes—the Thread
class for the thread-specific code and your Runnable implementation class for
your job-that-should-be-run-by-a thread code.
No comments :
Post a Comment