Before we talk about multithreading, let’s discuss threads. A thread is a light-weight smallest part of a process that can run concurrently with the other parts(other threads) of the same process. Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory. The process of executing multiple threads simultaneously is known as multithreading.
Let’s summarize the discussion in points:
1. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
2. Threads are lightweight sub-processes, they share the common memory space. In Multithreaded environment, programs that are benefited from multithreading, utilize the maximum CPU time so that the idle time can be kept to minimum.
3. A thread can be in one of the following states:
NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.
Read more about thread states at this link: Life cycle of threads
Multitasking vs Multithreading vs Multiprocessing vs parallel processing
If you are new to java you may get confused among these terms as they are used quite frequently when we discuss multithreading. Let’s talk about them in brief.
Multitasking: Ability to execute more than one task at the same time is known as multitasking.
Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
Creating a thread in Java
There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.
Before we begin with the programs(code) of creating threads, let’s have a look at these methods of Thread class. We have used few of these methods in the example below.
getName()
: It is used for Obtaining a thread’s namegetPriority()
: Obtain a thread’s priorityisAlive()
: Determine if a thread is still runningjoin()
: Wait for a thread to terminaterun()
: Entry point for the threadsleep()
: suspend a thread for a period of timestart()
: start a thread by calling its run() method
Method 1: Thread creation by extending Thread class
Example 1:
class MultithreadingDemo extends Thread{ public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ MultithreadingDemo obj=new MultithreadingDemo(); obj.start(); } }
Output:
My thread is in running state.
Example 2:
class Count extends Thread { Count() { super("my extending thread"); System.out.println("my thread created" + this); start(); } public void run() { try { for (int i=0 ;i<10;i++) { System.out.println("Printing the count " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("my thread interrupted"); } System.out.println("My thread run is over" ); } } class ExtendingExample { public static void main(String args[]) { Count cnt = new Count(); try { while(cnt.isAlive()) { System.out.println("Main thread will be alive till the child thread is live"); Thread.sleep(1500); } } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println("Main thread's run is over" ); } }
Output:
my thread createdThread[my runnable thread,5,main] Main thread will be alive till the child thread is live Printing the count 0 Printing the count 1 Main thread will be alive till the child thread is live Printing the count 2 Main thread will be alive till the child thread is live Printing the count 3 Printing the count 4 Main thread will be alive till the child thread is live Printing the count 5 Main thread will be alive till the child thread is live Printing the count 6 Printing the count 7 Main thread will be alive till the child thread is live Printing the count 8 Main thread will be alive till the child thread is live Printing the count 9 mythread run is over Main thread run is over
Method 2: Thread creation by implementing Runnable Interface
A Simple Example
class MultithreadingDemo implements Runnable{ public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ MultithreadingDemo obj=new MultithreadingDemo(); Thread tobj =new Thread(obj); tobj.start(); } }
Output:
My thread is in running state.
Example Program 2:
Observe the output of this program and try to understand what is happening in this program. If you have understood the usage of each thread method then you should not face any issue, understanding this example.
class Count implements Runnable { Thread mythread ; Count() { mythread = new Thread(this, "my runnable thread"); System.out.println("my thread created" + mythread); mythread.start(); } public void run() { try { for (int i=0 ;i<10;i++) { System.out.println("Printing the count " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("my thread interrupted"); } System.out.println("mythread run is over" ); } } class RunnableExample { public static void main(String args[]) { Count cnt = new Count(); try { while(cnt.mythread.isAlive()) { System.out.println("Main thread will be alive till the child thread is live"); Thread.sleep(1500); } } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println("Main thread run is over" ); } }
Output:
my thread createdThread[my runnable thread,5,main] Main thread will be alive till the child thread is live Printing the count 0 Printing the count 1 Main thread will be alive till the child thread is live Printing the count 2 Main thread will be alive till the child thread is live Printing the count 3 Printing the count 4 Main thread will be alive till the child thread is live Printing the count 5 Main thread will be alive till the child thread is live Printing the count 6 Printing the count 7 Main thread will be alive till the child thread is live Printing the count 8 Main thread will be alive till the child thread is live Printing the count 9 mythread run is over Main thread run is over
Thread priorities
- Thread priorities are the integers which decide how one thread should be treated with respect to the others.
- Thread priority decides when to switch from one running thread to another, process is called context switching
- A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
- A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
- To set the priority of the thread
setPriority()
method is used which is a method of the classThread
Class. - In place of defining the priority in integers, we can use
MIN_PRIORITY
,NORM_PRIORITY
orMAX_PRIORITY
.
Methods: isAlive() and join()
- In all the practical situations main thread should finish last else other threads which have spawned from the main thread will also finish.
- To know whether the thread has finished we can call
isAlive()
on the thread which returns true if the thread is not finished. - Another way to achieve this by using
join()
method, this method when called from the parent thread makes parent thread wait till child thread terminates. - These methods are defined in the
Thread
class. - We have used isAlive() method in the above examples too.
Synchronization
- Multithreading introduces asynchronous behavior to the programs. If a thread is writing some data another thread may be reading the same data at that time. This may bring inconsistency.
- When two or more threads need access to a shared resource there should be some way that the resource will be used only by one resource at a time. The process to achieve this is called synchronization.
- To implement the synchronous behavior java has synchronous method. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object. All the other threads then wait until the first thread come out of the synchronized block.
- When we want to synchronize access to objects of a class which was not designed for the multithreaded access and the code of the method which needs to be accessed synchronously is not available with us, in this case we cannot add the synchronized to the appropriate methods. In java we have the solution for this, put the calls to the methods (which needs to be synchronized) defined by this class inside a synchronized block in following manner.
Synchronized(object) { // statement to be synchronized }
Inter-thread Communication
We have few methods through which java threads can communicate with each other. These methods are wait()
, notify()
, notifyAll()
. All these methods can only be called from within a synchronized method.
1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a box which can hold only one thread. Once a thread enters the monitor all the other threads have to wait until that thread exits the monitor.
2) wait()
tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify()
.
3) notify()
wakes up the first thread that called wait()
on the same object.
notifyAll()
wakes up all the threads that called wait() on the same object. The highest priority thread will run first.
References
- The Complete Reference Java 2 by Herbert Schildt
vinod says
hi
i am not understanding the concept of Example program 2.
can you please explain about this.
thank you
jugal says
in second example : thread is creating by extend the thread keyword. This will create new thread class .Now your Count class working as thread as in above.
maha says
plz explain this line of code :
super(“my extending thread”);
plz explain in detail why the super keyword is doing here ????????????
Aki says
because it is use to differentiate the base class method from child class method :)
Gaurav says
Basically super keyword refer to the Base class. super always will give priority to the base class.
Yaser says
super(“my extending thread”); will call the superclass’s constructor from extending class. So it invokes Thread(“my extending thread”);
Rohith says
We are calling base class constructor with parameter “my extending thread” in the super class
jugal says
see proper concept.
Stephen says
I can’t understand the concept of run() and start() method.
DArshit says
Hey Stephen whenever you will start thread by .start() method it will then first execute its run() method of that thread .
abhay says
Basically run is a method in thread class.
And whenever we call .star() it will override the run() from thread class
Sunita says
start() is used to start the execution of the code written in run(). If you will omit start() the code inside run() will not be executed.
Rajneesh says
if you create a thread and you simply use run() method then it will run on the main thread but if you do use start() then the thread will not run in the main thread.
anu says
I cant get what is the difference between creating thread class & implementating runnable interface?
Chaitanya Singh says
There is no difference. It all depends on the need and requirements. Let me explain this to you with an example.
Java doesn’t support multiple inheritance, which means you can only extend (inherit) one class so once you extend the Thread class you cannot extend or inherit another class in Java. As per object oriented programing(OOPs), the whole purpose of inheritance is to add new functionality, modifying or improving behaviors by overriding methods of parent class. If we are not making any modification on Thread then using Runnable interface should be your choice instead of extending Thread class. There are few more things to discuss regarding this. I will cover them in detail in a separate post. I hope this makes sense now.
Smith says
Thanks I will love to be a friend
Bhushan says
how can we execute multiple threads in parallel? if i want to access two/more files at the same time to minimize execution time ?
Roshan Singh says
Threads do not run absolute concurrent way but they overlap to minimize CPU wastage…..
moni says
i want to know the types of multithreading in java
vinoth says
Can any one explain me about Thread Pool concept?
Joe says
Take a look at: http://stackoverflow.com/questions/8767527/how-to-use-thread-pool-concept-in-java
sai says
Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
Advantage of Java Thread Pool:
Better performance It saves time because there is no need to create new thread.
shahid malik says
Suppose there are two files in the system containing some textual data, your program should read
these files concurrently and merge them into one file using JAVA threads. The file should be merged
in such a way that it contains one line of first file and one line of second file.
Philip Fasan says
Do you offer pdf versions of this material? This can help when the network is not performing.
ujwala says
i want know the thread class and runable class
Lalit Kumar says
Hi brother, I have been going though all your post. From my point of view this the best website to learn anything from zero. Keep posting new stuffs.
Mitul Thesiya says
I’m running TestNG mechanism to run parallel thread for executing my testcases. Here, i.e. for 3 parallel threads, if suppose 2nd thread is caught by any error and need to suspend till execution of remaining 2 parallel threads, could you guide how can I achieve to facilitate and support TestNG valid mechanism for parallel testing in this case?
Ravindra Patle says
C:\Program Files\Java\jdk1.8.0_66\bin>javac threadaction.java
threadaction.java:3: error: error while writing A: A.class (Access is denied)
class A extends Thread
^
Note: threadaction.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
Why this error is showing ? Please help me…
Thanks in Advance..
Utsav Oza says
Where can I use Multi-Threading in my java based social networking Project.
Himani rajput says
Give the different example of synchronized method of thread
lastav says
its better to use lambda expressions (JDK 1.8 only)
makes code easier to understand
Anand Pandey says
Best example of Multi Threading and Multi Tasking :
Suppose you have open two browser google chrome and Mozilla Firefox inside the chrome you have 4 tabs so you have two programs those are running simultaneously is multi processing but inside one program i.e. chrome you have 4 tabs that is multi threading.