Java – Creating Thread

Home/Java - Tutorial/Java - Multithreading/Java – Creating Thread
Java – Creating Thread 2017-08-09T13:45:50+00:00

Java Creating Thread :

We can create thread in java with two different ways.

1. Extending the Thread Class.

2. Implements runnable interface.

lets try to understand step by step both of this.

1. Extending the Thread class:

In this method one normal class extends the inbuilt class thread and override its run() method with the code required by that particular thread.

Here we are going to extend class java.lang.Thread. so we can access all the methods of thread class.

Create one class which extends the thread class.

Override the run method and put lines  of code inside thread method that will be perform by thread.

Create an object of class which we created with extending the thread class and call the start() method to execute the thread.

Class MyThread extends Thread

{

………………..

………………..

}

So now we have one thread named MyThread.

Implementing the run() method

Public void run()

{

………

// Thread code here

}

Starting new Thread

MyThread aTh = new MyThread(); // it instantiates a new object of class MyThread

aTh.start();                                // invokes run() method

EX:

 

 


Output 1:

Thread A

From thread A i = 1
From thread A i = 2
From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A
End of main thread
Thread B
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B
Output 2:
Thread A
From thread A i = 1
From thread A i = 2
End of main thread
From thread A i = 3
From thread A i = 4
Thread B
From thread A i = 5
From thread B i = 1
Exit from A
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B
Here you can see that both outputs are different though our program code is same.
It happens in thread program because they are running concurrently on their own.
Threads are running independently of one another and each executes whenever it has a chance.

2. Implementing the Runnable interface:

In this method we have one interface named runnable and we implements this interface for implement a thread.

Create one class which implements runnable interface.

Override the run() method and put some line of code for that particular thread.

Now create an object of inbuilt thread class and create an object of class that implements runnable interface.

Give the reference of object to thread object by passing an argument (argument must be the object of class which implements the runnable interface) while creating a thread object.

Call the start() method to run the thread.

EX:

 


Output :
End of main Thread
Inside X thread
From xthread i = 1
From xthread i = 2
From xthread i = 3
From xthread i = 4
From xthread i = 5
From xthread i = 6
From xthread i = 7
From xthread i = 8
From xthread i = 9
From xthread i = 10
Exit from X

Prev Next