days
-1
-8
hours
0
-3
minutes
-2
-7
seconds
-1
-7
search
Tutorial alert!

Creating a thread: Extending thread vs implementing runnable

Ethan Millar
thread
Large cog wheels in the motor image via Shutterstock

Every point about Thread discussed in this piece is meant to make readers understand the concept of Thread and its uses, together with its advantages and disadvantages.

This article tells the story of the thread and explains its major advantages, disadvantages, and uses. You will learn from proficient Java programmers how to create a thread using Extends Thread class and Implements Runnable interface. 

Advantages of thread

  • Reduces development time.
  • Reduces maintenance costs.
  • Improves the performance of complex applications.
  • Useful for improving the responsiveness of the user interfaces.
  • Used in server applications to improve high throughput and resource utilization.
  • Parallelize tasks.
  • If a thread cannot use all the computing resources of the CPU (because instructions depend on each other’s result), running another thread can avoid leaving these idle.
  • Take advantage of multiprocessor systems

Disadvantages of thread

  • Multiple threads can interfere with each other when sharing hardware resources such as caches or translation lookaside buffers (TLBs).
  • Execution times of a single thread can be degraded, even when only one thread is executing. This is due to slower frequencies and/or additional pipeline stages that are necessary to accommodate thread-switching hardware.
  • Hardware support for multithreading is more visible to software, thus requiring more changes to both application programs and operating systems than multiprocessing.

Uses of Thread

  • Java applications are naturally threaded. The runtime environment begins the execution of the program with the main() method in one thread. Garbage collection takes place in another thread. Screen updating occurs in a third thread. There may be other threads running as well, mostly related to the behavior of the virtual machine. All of this happens invisibly to the programmer. Sometimes you’re only concerned with what happens in the primary thread which includes the main() method of a program. If this is the case, you may not need to worry about threading at all.
  • The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to utilize the CPU time as much as possible. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread. Each thread has a separate path of its execution. This way a single program can perform two or more tasks simultaneously.
  • Threads are lightweight processes; they share the same address space. In a Multithreaded environment, programs make maximum use of CPU so that the idle time can be kept to a minimum.
  • To perform asynchronous or background processing.

SEE ALSO: Thread magic tricks: 5 things you never knew you can do with Java threads

Thread

The Thread class is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Most important points can be found below:

  • Every thread has a priority. Threads with higher priority are executed before those with lower priority
  • Each thread may or may not also be marked as a daemon.
  • There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread;
  • The other way to create a thread is to declare a class that implements the Runnable interface.

Thread class provides constructors and methods to create and perform operations on a thread class. Thread class extends Object class and implements Runnable interface.

Constructors of Thread class

1. Thread( )

2. Thread(String str)

3. Thread(Runnable r)

4. Thread(Runnable r, String str)

Thread class defines many methods for managing threads. Some of them are:

Method Description
setName() to give thread a name
getName() return thread’s name
getPriority() return thread’s priority
isAlive() checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified time
start() start a thread by calling run() method

 

There are two ways to create a thread:

  • extends Thread class
  • implement Runnable interface

1. Extends Thread class

Create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.

public class MyThread extends Thread{
	 public void run()
	 {
	  System.out.println("Thread started running..");
	 }
	 public static void main( String args[] )
	 {
		MyThread mt = new  MyThread();
	  	mt.start();
	 }
}

Output :

Thread started running..

In this case, we must override the run() and then use the start() method to start and run the thread. Also, when you create MyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class object acts as Thread class object.

We call run() method directly without using start() method

public static void main(String args[])
 {
	  MyThread mt = new MyThread();
	  mt.run();
 }

The thread won’t be allocated a new call stack, and it will start running in the current call stack, that is the call stack of the main thread. Hence Multithreading won’t be there.

We Start a thread twice

Thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.

public static void main( String args[] )
{
      MyThread mt = new MyThread();
      mt.start();
      mt.start();     //Exception thrown
}

When a thread is in running state, and you try to start it again, or any method try to invoke that thread again using start() method, exception is thrown.

2. Implementing the Runnable Interface

The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is 

public void run()

  • run() method introduces a concurrent thread into your program. This thread will end when run() returns.
  • You must specify the code for your thread inside run() method.
  • run() method can call other methods, can use other classes and declare variables just like any other normal method.

class MyThread implements Runnable {

public void run() {
		System.out.println("Thread started running..");
	}

	public static void main(String args[]) {
		MyThread mt = new MyThread();
		Thread t = new Thread(mt);
		t.start();
	}
}

Output :

Thread started running..

To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program.

Ending Thread

A Thread ends due to the following reasons:

  • The thread ends 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

  • At times when more than one thread tries to access a shared resource, we need to ensure that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.
  • The synchronization keyword in Java creates a block of code referred to as critical section.
  • By using this 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.

Syntax

synchronized (object) {
	//  Statement to be synchronized
}

Use Synchronization

  • If we do not use synchronization and let two or more threads access a shared resource at the same time, it will lead to distorted results.
  • Here is an example: Let’s assume that we have two different threads T1 and T2, T1 that start execution and save certain values in a file sample.txt which will be used to calculate some results when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 changes the values saved by T1 in the file sample.txt (sample.txt is the shared resource). Now obviously T1 will give the wrong result.
  • Synchronization was introduced to prevent such problems from happening. If we use synchronization in the above-mentioned case, once T1 starts using sample.txt file, this file will be locked(LOCK mode), and no other thread will be able to access or modify it until T1 returns.

Deadlock

  • Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in a different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.
  • 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.

Every point about Thread discussed by Java programmers here is meant to make you understand the Thread and its uses along with disadvantages and benefits. 

Author

Ethan Millar

Ethan Millar has been working with AegisSoftTech as a Content Creator for the past 5 years. He has a vast experience in writing technical articles for Java, Hadoop, .Net and MS Dynamics CRM. You can find him on Facebook and Google Plus.


Leave a Reply

Be the First to Comment!

avatar
400
  Subscribe  
Notify of