- Java Thread By Extending Thread Class – Java Tutorials
- Thread extending in java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Basics: All about Java threads
- Risk Factor
- Threads in Java
- Thread creation in Java
- 1) By extending thread class
- 2) By Implementing Runnable interface
- Extends Thread class vs Implements Runnable Interface?
- Thread life cycle in java
- Ending Thread
- Synchronization of Threads
- Deadlock
- Guidelines for synchronization
- Top Related Articles:
- About the Author
Java Thread By Extending Thread Class – Java Tutorials
Java Thread by extending Thread class – Here we cover the complete tutorial and examples for java thread by extending thread class.
Generally, thread facilities are provided to a class in two ways:
In this page, we just concentrate more on extending Thread rather than implementing Runnable.
The class Thread helps to achieve multi threading. We can inherit Thread class to provide multi threading features to a class.
For Example:
When an object of the above class is created, that object contains Thread facilities. Once such an object is started the control creates a separate branch (Thread) and executes the code in that branch.
For Example:
The start method initiates a new branch, and starts the corresponding run() method. We should override the run() method in the corresponding class (Root here).
For Example:
For Example:
In the above program we have created an object of class Root and started it. When the thread is started the run() method of Root is executed in a separate branch (thread) and at the same time the remaining code in main() method is also executed.
The code in run() prints letters and at the same time the code in main() prints numbers. As both the codes execute simultaneously, we can see both (letters and numbers) printed together.
When we inherit the Thread class, the facilities (methods) of that class will be available to the sub class. The features include
Method name | Functionality |
sleep(long) | suspends execution for the specified amount of time |
sleep(long,int) | suspends execution for the specified amount of time |
activeCount(); | returns the number of threads active currently |
start(); | creates new branch(thread) and invokes the corresponding run() method |
run(); | Actual code of the Thread is written here by us (programmer) in our thread class. The run() method in Thread class is just a dummy method and we override it in our class. |
isAlive(); | tells us whether the invoking object (Thread) is active or not. If the object is in running state, the method returns true. If the thread object is created but not yet started then the method returns false. If the thread execution is completed then also the method returns false. |
setPriority(int); | allows setting the priority of the thread. This method receives the priority (an integer) and sets it. the allowed range of values is from 1 to 10 where 1 indicates minimum priority and 10 indicates maximum priority. By default a thread holds a priority of 5 (normal priority) |
getPriority(); | gives us the current priority value of the thread |
setName(String); | allows us to set a name to the thread. By default a thread gets a name in sequence (like Thread-0, Thread-1, etc) after the main thread. If we want any specific name to a thread then we can specify it as a string. |
getName(); | returns a string that represents name of the thread |
join(long) | same as join() but allows the programmer to specify some time so that the main thread resumes its operation after the specified time (if the invoking thread has not completed execution) |
join(long,int) | same as join(long) but we can specify the amount of time to wait in nanoseconds also. |
join() | It makes the current thread wait till the invoking thread completes its execution. Suppose we are in main thread and created another thread and started it. |
Out of the above mentioned methods, sleep(long), sleep(long,int), join(), join(long) and join(long,int) would throw an InterruptedException.
So we should take care of handling the situation when these methods are used.
Similarly start(), setName(String), join(long) and join(long,int) are synchronized methods. So cannot use them parallel on a single Thread object.
The sleep(long), sleep(long,int) and activeCount() are static methods so they can be used without creating an object of Thread.
isAlive(), setPriority(int), getPriority(), setName(String), getName(), join(long), join(long,int), join(), setDaemon(boolean) and isDaemon() are final methods. So we cannot overwrite them.
All of them (mentioned above) are public methods so we can accessed from anywhere.
If you have any doubts related to Java Thread by extending Thread class and examples which we shared above just do leave a comment here.
Thread extending in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Basics: All about Java threads
When a thread is invoked, there will be two paths of execution. One path will execute the thread and the other path will follow the statement after the thread invocation. There will be a separate stack and memory space for each thread.
Risk Factor
- Proper co-ordination is required between threads accessing common variables [use of synchronized and volatile] for consistence view of data
- overuse of java threads can be hazardous to program’s performance and its maintainability.
Threads in Java
Java threads facility and API is deceptively simple:
Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or by instantiating classes that extend the Thread class.
Thread creation in Java
Thread implementation in java can be achieved in two ways:
Note: The Thread and Runnable are available in the java.lang.* package
1) By extending thread class
- The class should extend Java Thread class.
- The class should override the run() method.
- The functionality that is expected by the Thread to be executed is written in the run() method.
void start(): Creates a new thread and makes it runnable.
void run(): The new thread begins its life inside this method.
public class MyThread extends Thread < public void run()< System.out.println("thread is running. "); >public static void main(String[] args)
2) By Implementing Runnable interface
- The class should implement the Runnable interface
- The class should implement the run() method in the Runnable interface
- The functionality that is expected by the Thread to be executed is put in the run() method
public class MyThread implements Runnable < public void run()< System.out.println("thread is running.."); >public static void main(String[] args)
Extends Thread class vs Implements Runnable Interface?
- Extending the Thread class will make your class unable to extend other classes, because of the single inheritance feature in JAVA. However, this will give you a simpler code structure. If you implement Runnable, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
- If you just want to achieve basic functionality of a thread you can simply implement Runnable interface and override run() method. But if you want to do something serious with thread object as it has other methods like suspend(), resume(), ..etc which are not available in Runnable interface then you may prefer to extend the Thread class.
Thread life cycle in java
Ending Thread
A Thread ends due to the following reasons:
- The thread ends when it comes when the run() method finishes its execution.
- When the thread throws an Exception or Error that is not being caught in the program.
- Java program completes or ends.
- Another thread calls stop() methods.
Synchronization of Threads
- In many cases concurrently running threads share data and two threads try to do operations on the same variables at the same time. This often results in corrupt data as two threads try to operate on the same data.
- A popular solution is to provide some kind of lock primitive. Only one thread can acquire a particular lock at any particular time. This can be achieved by using a keyword “synchronized” .
- By using the synchronize only one thread can access the method at a time and a second call will be blocked until the first call returns or wait() is called inside the synchronized method.
Deadlock
Whenever there is multiple processes contending for exclusive access to multiple locks, there is the possibility of deadlock. A set of processes or threads is said to be deadlocked when each is waiting for an action that only one of the others can perform.
In Order to avoid deadlock, one should ensure that when you acquire multiple locks, you always acquire the locks in the same order in all threads.
Guidelines for synchronization
- Keep blocks short. Synchronized blocks should be short — as short as possible while still protecting the integrity of related data operations.
- Don’t block. Don’t ever call a method that might block, such as InputStream.read(), inside a synchronized block or method.
- Don’t invoke methods on other objects while holding a lock. This may sound extreme, but it eliminates the most common source of deadlock.
Target keywords: Java threads, javathread example, create thread java, java Runnable
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.