Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Java Threads in Web Application

We will learn today the process to create Java thread, execute it and finally to extend the Java thread class.

What is Multithreading? It actually defines two or more tasks running at the same time and that too within a single program. What is a thread? It is actually an independent route of execution within a program. There can be lot of threads that can be implemented or executed concurrently within a program. Each of the Java thread is created and controlled by the java.lang.Thread class. The Java threads can be executed asynchronously or synchronously.

Benefits of Multithreading:

Let us have a look at the advantages that multithreading brings in when we compare to multiprocessing. The very first advantage is that the threads are very lightweight and they share the same address space thereby have the ability to share both data and code. As far as cost is concerned, it is cheap to do a context switching between threads. Also the price of thread intercommunication is less when we compare to multiprocessing. The last but definitely not the least we have threads that permit different tasks that can be performed concurrently.

How to create a Thread?

The below lists the ways to create thread in java:

  • Execute the Runnable interface (java.lang.Runnable)
  • By elongating the Thread class (java.lang.Thread)

How to Execute the Runnable Interface?

The below lists the Runnable Interface Signature

Listing 1: Interface Signature

public interface Runnable {
void run();
}

The best way to generate a java thread is to implement the Runnable Interface. Post this, we instantiate an object of the class. There is a need to override the run() method into our class. This is one and only method that needs to be implemented and comprise of the run() method that consists of the logic of the thread.

Steps to create threads based on the Runnable interface:

  • Step 1: We have a class that runs the Runnable interface and provides a run() method. This need to be executed by the thread and an object of this class is a Runnable object.
  • Step 2: Now, you need to create an object of Thread class. This is done by passing a Runnable object as argument to the Thread constructor making the thread object a Runnable object that executes the run() method.
  • Step 3: This step will invoke the start() method on the Thread object that is created in the earlier step and this method returns immediately post the spawning of a thread.
  • Step 4: The process completes with the run() method either by normal completion or by throwing an uncaught exception.

We have a program below that describes the execution of threads. This is done by making use of a runnable interface instead of extending the Thread class. In order to initiate the thread, there is a need to invoke the start() method on the object you are working on.

Listing 2: Executing a Thread

class RunnableThread implements Runnable {

	Thread runner;
	public RunnableThread() {
	}
	public RunnableThread(String threadName) {
		runner = new Thread(this, threadName); // New Thread Creation.
		System.out.println(runner.getName());
		runner.start(); // Thread Initiation
	}
	public void run() {
		// Exhibiting details on the specific thread
		System.out.println(Thread.currentThread());
	}
}

public class RunnableExample {

	public static void main(String[] args) {
		Thread thread1 = new Thread(new RunnableThread(), "thread1");
		Thread thread2 = new Thread(new RunnableThread(), "thread2");
		RunnableThread thread3 = new RunnableThread("thread3");
		//Start the threads
		thread1.start();
		thread2.start();
		try {
			// one second lag
			Thread.currentThread().sleep(1000);
		} catch (InterruptedException e) {
		}
		// Main thread displaying
		System.out.println(Thread.currentThread());
	}
}

Here is the Output:

thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private

The approach used above to create a thread making use of the Runnable Interface is recommended at the time when the class being used to instantiate the thread object is required to extend some other class.

How to Extend Thread Class?

The below steps lists the process to create threads depending on extending the Thread:

Step 1: We have a class that extends the Thread class and overrides the run() method from the Thread class. This is done in order to define the code executed by the thread.

Step 2: You need to make use of a subclass that is required to call a Thread constructor explicitly in its constructors so as to begin the thread making use of the thesuper() call.

Step 3: Make use of the start() method that is inherited from the Thread class so as to invoke on the class object in order to make the thread eligible for running.

The below code represent the execution of threads by extending the Thread class instead of executing the Runnable interface. In order to initiate the thread, there is a need to invoke the start() method on the object you are working on.

Listing 3: Extend the Thread Class

class XThread extends Thread {

	XThread() {
	}
	XThread(String threadName) {
		super(threadName); // Initialize thread.
		System.out.println(this);
		start();
	}
	public void run() {
		//Display info about this particular thread
		System.out.println(Thread.currentThread().getName());
	}
}

public class ThreadExample {

	public static void main(String[] args) {
		Thread thread1 = new Thread(new XThread(), "thread1");
		Thread thread2 = new Thread(new XThread(), "thread2");
		//	    The below 2 threads are assigned default names
		Thread thread3 = new XThread();
		Thread thread4 = new XThread();
		Thread thread5 = new XThread("thread5");
		//Start the threads
		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
		try {
	//The sleep() method is invoked on the main thread to cause a one second delay.
			Thread.currentThread().sleep(1000);
		} catch (InterruptedException e) {
		}
		//Display info about the main thread
		System.out.println(Thread.currentThread());
	}
}

Here is the Output:

Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]

Conclusion

We learned today the importance of Java threads in Web Application and the way to create, execute and extend a thread class.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login