In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways:

For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:
The following program demonstrates a single thread creation extending the "Thread" Class:
class MyThread extends Thread{
|
| C:\j2se6\thread>javac
RunThread.java C:\j2se6\thread>java RunThread Thread started.... |
II. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows:
The following program demonstrates the thread creation implenting the Runnable interface:
class MyThread1 implements Runnable{
|
However, this program returns the output same as of the output generated through the previous program.
Output of the Program is:
| C:\j2se6\thread>javac
RunableThread.java C:\j2se6\thread>java RunableThread Thread started.... |
There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:
join() & isAlive() methods:
The following
program demonstrates the join() & isAlive() methods:
class DemoAlive extends Thread {
|
Output of this program is:
| C:\j2se6\thread>javac DemoJoin.java C:\j2se6\thread>java DemoJoin Wait for the child threads to finish. Thread a: 0 Thread b: 0 Thread a: 1 Thread b: 1 Thread a: 2 Thread b: 2 Thread a: 3 Thread b: 3 Thread a: 4 Thread b: 4 Exit from thread: Thread a Thread A not alive. Exit from thread: Thread b Thread B not alive. Exit from Main Thread. C:\j2se6\thread> |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Thread Creation View All Comments
Post your Comment