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

Java Threads: Understanding the concept

In this article we will learn about the basic concepts of threads and its implementation in Java language.

We see different peoples in our daily life, they multiple task at a time, I mean they watch television, and at the same time they are also busy in their handset, or people drive while talking on phone. How do our mind does this, how do we focus on both the things, well , let this be a question for Scientists.

In the domain of object oriented programming this sort of multitasking , can be achieved , that is simply using threads.So before going in details of threads we need to understand some basic concepts of process, this because the threads run within a process and if we do not about the process , it would not be easy for us to understand threads.

What is a Process:

When we make any sort of application , it consist of processes, so a simple application may consist of single processes but a complex and relatively large application would consist of many process. Process in its most simplest form is a program that is in execution. Now you may wonder, how, suppose you open up any picture in picture viewer software, so there is process running in that application. Because we know that application consist of process, in the same all the application uses process.

Processes can run independently of each other, one process can not access the memory of the other process directly.

Threads:

Threads are contained in the process, or we can say that they are the basic units in process which can keep the processor busy for a certain amount of time while they are executing i.e processor is allocated to threads. This processor allocation is done by the OS (Operating System). Threads in a process can be programmatically scheduled, that is specifying their order of their execution.

Note: There is always one thread that commences the process, that thread is called the Default thread, or the Primary thread.

Things that should be kept in mind while dealing with threads

  • Threads always run in sequence , If there are many threads and we want to run them one thread will run at a time only.
  • If due to any condition any thread is blocked or destroyed, other threads have ability to run.
  • Threads unlike processes are not independent of each other, they depend on each other.
  • Threads unlike processes can share their resource with each other, that is two threads can access the same memory blocks .
  • Threads unlike processes are always in position to support each other.

How to create Threads:

To create threads, we have to keep in mind few things:

There are two methods or ways to create a thread.

By using the thread class

In this way, we extend our class from the java.lang.thread class, and then implement ther run methods of the thread class to get our desired output.

By using the Runnable interface.

In this way, we implement an interface java.lang.Runnable.

Thread class can be used to create threads but it have it limitation , that is since java does not support multiple inheritance so , if suppose class B extends class A and we want to create a thread in this class it would not be possible because we cannot write code class B extends class A extends Thread . so to overcome this problem we use the second methods that is widely used , allowing us to create threads, the way, and where we want to create.

Program to create thread by implementing the Runnable interface

Listing 1: ThreadsByRunable.java

public class ThreadsByRunable implements Runnable {
	int count=0;
	public static void main(String[] args) {
       ThreadsByRunable thread1 = new ThreadsByRunable();
		Thread th1 = new Thread(thread1);
		th1.start();
	}
	public void run() {
		System.out.println("this is thread"+Thread.currentThread().getName());
		while(count<=10){			
			System.out.println("thread"+(++count));
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}
		}   
}
}

Output listing 1: ThreadsByRunable.java

this is threadThread-0
thread1
thread2
thread3
thread4
thread5
thread6
thread7
thread8
thread9
thread10
thread11

Explanation to code listing 1: ThreadsByRunable.java

We first of all created a class that implement a interface Runnable, now it contain only one method, that is to be implemented, this method is run method, we displayed the name of the thread and simply used while loop to show the count value. After every count value we let the thread to sleep for 1000 milliseconds.

Now coming to Main() function, here we first created a object of ThreadsByRunable class and then passed the object as argument to thread object. Now who’s ever object is passed as argument to the thread object its run method will be executed.

The run method will be executed when th1.start();

Program to create thread by Extending java.lang.thread class

Listing 2: ThreadsByInheritance.java

public class ThreadsByInheritance extends Thread{
	private int count=0;
	public void run() {
	System.out.println("wellcome thread1 ");
	while(count<=10){
		System.out.println("thread"+(++count));
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	}
	public static void main(String[] args) {
		ThreadsByInheritance th1= new ThreadsByInheritance();
		th1.start();
	}
}

Output: Listing2: ThreadsByInheritance.java

wellcome thread1
thread1
thread2
thread3
thread4
thread5
thread6
thread7
thread8
thread9
thread10
thread11

Explanation Listing2: ThreadsByInheritance.java:

Now in this program we did not pass the object we simply extended our class from the thread class, so we got all the capabilities of the thread class. Just by using the following code we run the thread:

ThreadsByInheritance th1= new ThreadsByInheritance();
		th1.start();

See the object of thread class in not created only we make use of the object of ThreadsByInheritance class, this is because we inherited the thread class.

Methods of Threads class:

Thread class has many methods that can be used to get different information about thread that running is in the next example, we will use few of the following methods , which show so that you get an idea of how to use the methods of the thread class.

activeCount():

Is one the method from thread class that return Boolean value of either true or false, if your thread is active that is running it will return true otherwise false.

currentThread():

This method is used to return the reference of the current thread, and it can be used with one of the other method that is getname() to get the name of the current thread’s name.

setname(String argument):

This method of thread class is used to set the name for the thread , it takes one argument that is to be a string.

sleep(long millis, int nanos):

This method can be used to tell the thread to sleep for specific interval of time, it can ether take one argument of milliseconds, or two arguments for the nanoseconds. In the example below we have used milliseconds.

Start():

This method tells the threads to start the execution.

Listing 3: ThreadsByInheritance.java (usage of methods of thread class)

public class ThreadsByInheritance extends Thread{
	private int count=0;
	String name;
	public void run() {
		
	System.out.println("wellcome thread1 ");
	while(count<5){
		
		System.out.println("thread "+(++count)+" name = "+Thread.currentThread().getName());
		
		name = Thread.currentThread().getName();
		System.out.println("Thread.currentThread().getName() = "+name);
		
		if(name.equals("trustingeeks.com")){
			
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
	
	}
	}
	

	public static void main(String[] args) {

		ThreadsByInheritance th1= new ThreadsByInheritance();
		System.out.println(th1.isAlive());
		th1.setName("Mrbool.com");
		th1.start();
		System.out.println(th1.isAlive());
	}

}

Output:

false
true
wellcome thread1
thread 1 name = Mrbool.com
Thread.currentThread().getName() = Mrbool.com
thread 2 name = Mrbool.com
Thread.currentThread().getName() = Mrbool.com
thread 3 name = Mrbool.com
Thread.currentThread().getName() = Mrbool.com
thread 4 name = Mrbool.com
Thread.currentThread().getName() = Mrbool.com
thread 5 name = Mrbool.com
Thread.currentThread().getName() = Mrbool.com

Explanation of the above code:

As you can see that we called isActive() before Start() method, so the output is shown false , but when we called the same method after the start() method, it output changes to true, we have declared one string field that is used, to get the name of the thread using Thread.currentThread().getName()

Which we had set in the main() method to be Mrbool.com .

And in the loop we have also used the sleep method to sleep thread for 1000 milliseconds, for doing so we have also used the try and catch blocks for exception handling .

Conclusion:

In this tutorial we used got the basic concept of threads in java, and got the idea how to create threads in different ways.

To further study the methods and constructors of the threads class visit the documentation.

Note: In professional development threads are most often created with help of implementing interface that is Runnable interface, not by inheriting your main class from the Java.lang.Thread because jave is famous that it does not support multiple inheritance , so that is why one should use the first approach for creating threads.

See also



computer science Graduate :Ceo at www.gigsclerk.com (Best Marketplace to Buy and sell service online from 2$-100$ ) and www.trustingeeks.com. Interested in programming, online buissiness. Android development.

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