Search

Multithreading in Java



Multithreading in Java

  • The aim of multithreading is to achieve the concurrent execution.
  • A flow of control is known as thread
  • The purpose of thread is to execute the logic of the java program which is written in the form of user defined method concurrently
  • If a java program is containing multiple flow of control then it is known as multithreaded program
  • The languages like c, c++, Pascal, Cobol are treated as single threaded modeling languages because these execution environment contains single flow of control, provides sequential execution, takes more execution time and doesn’t contain any library for development of multithreading application.
  • The languages/technologies like java and .net are treated as multithreaded modeling language because these execution environments provides multiple flow of control and gives concurrent execution, gives less execution time and contains an effective library for development of multithreading based applications.
We use the following api for development of multithreaded application

(a) Java.lang.Thread class
(b) Java.lang.Runnable interface

Whenever we write a java program there exist two types of thread they are..

(a) Foreground thread
(b) Background thread
  • A foreground thread is one which is always executing the logic of the java program which is written in the form of user defined method concurrently.
  • A background thread is one which is monitoring the execution status of the thread
  • By default there exist single foreground and programmatically there is a possibility of existing multiple foreground threads for executing the method concurrently and recommended to have single background thread.
  • The real world implementation of multithreading concept is to develop real world server software. In other word most of the real world server software like tomcat, weblogic etc.. are developed by server software venders In java language with multithreading concept.

Hence multithreading of java is one of the specialized forms of multitasking of operating system.

Que. How do you justify each and every java program is multithreaded

Ans. When we execute any java program, for executing the logic of the java program they internally there exist one of the thread known as foreground.

To monitor the execution status of foreground thread, internally one more thread is created known as background thread. So a java program is containing two threads by default hence and java program is called multithreaded.

Que. What are the difference between program and process?


Program Process
  1. Set of optimized instruction A program Is under execution are known as program is known as process
  2. Programs resides in secondary memory Process resides in main memory
  3. Program exist in secondary memory A process is resides in main memory for long time until be delete for limited span of time
  4. Pro grammatically a program can A process concern as a dynamic object be concern as a static object
Que. Define heave weight component and light weight component
Ans. Heave weight components takes more processing time where as light weight component takes less processing time.

Process based and thread based application or non-multitasking and multitasking application

As programs in the industry we may write two types of application they are
  1. Process based / non-multitasking applications
  2. Thread based / multitasking applications 
PBA and TBA

Definitions of address space:
It is an amount of temporary memory space created by operating system on the stack memory for the execution of the method.

Definitions of context switch:
  • The mechanism of switching the control of cpu from one address to another address space is known as context switch.
  • For the best application context which must be less

Note: each and every thread based application is one of the process based application in which there exist one main process and the main process in term creates multiple sub processes in java programming point of view the main process is known as thread group name and the sub processes are called foreground thread.


A process based application is not a thread based application because purely a process based application contains single flow of control.

Diagrametically

State / Life cycle of thread


The number of stages or braking points occurring in the thread execution is known as state of a thread.

State of a thread are classified into five types they are
  1. New state
  2. Ready state
  3. Running state
  4. Wating state
  5. Halted state

State chat diagram

New state:

In new state thread is created and about to enter into main memory.

Ready state:
In ready state thread will be entered into main memory, memory space is allocated for the thread and 1st time waiting for the CPU.

Running state: 
In running state the thread is under control of the CPU in the word a thread is entered into under the control of CPU for the amount of CPU burst time the state of the thread is called running.

Halted state:
In halted state the thread is completed its total execution.

Waiting state:
A thread is said to be in waiting state if and only if it satisfies any of the following factors

a. Thread will come to waiting state for the remaining CPU burst time. (it an amount of time required by the thread from the CPU. It is decided by operating system)

b. Suspending the currently execution thread.

c. Making the currently executing thread to sleep

By specifying an amount of time in term of millisecond (1 sec=1000 millisecond)

d. Making the currently executing thread to wait with time.

e. Making the currently executing thread to wait without time.

f. Joining the threads.

Que. How do you justify threads of java executes concurrently.
Ans. If thread of java execution with the difference of hour by hour, minute by minute and second by second then such thread execution is called sequential execution because a java program ca differentiate the difference of hours, minute and seconds and it is one of the slower execution`
  • If thread of java executions with the difference of millisecond by the cpu the such thread executions is known as concurrent execution because java program is unable to differentiate the difference of millisecond of time and it is considered a faster execution.

Hence in java programming environment threads of java executes concurrently with the difference of millisecond of time by following round robin algorithms.

Hence the state of the thread, ready, running and waiting state are called in-memory state and whose execution status is true where as new and halted sates are called out-memory state and whose execution state is false.

Creation of thread:

We know that a flow of control is known as thread and it is ment for executing
The logic of the java program which is written in the form of user defined methods concurrently.
In java programming we are having two approaches to create a thread they are
  1. By using java.lang.Thread class
  2. By using java.nalg.Runnable interface.

By using java.lang. Thread class

By using.lang.Thread class one can create its object in three ways they are

(a) Directly with new operator

e.g Thread t1=new Thread();

(b) By using factory method

e.g Thread t2=new Thread.currentThread();

(c) Object of sub class of thread class is an object of thread class.

e.g class Th1 extends Thread


{
--------
--------
--------
}

Th1 t1=new Th1();


Here t1 is an object of Th1 class and Th1 is the sub class of thred class and hence indirectly t1 is an indirect object of Thread class.

Profile of java.lang.Thread class

Data member
Internally flow of threads

When we write any multithreading program, there is a possibility of existing multiple threads. When these threads are under execution, internally they follows the sequence of steps.
  1. Java program start executing.
  2. Jvm creates thread group name and it always resides in main method.
  3. Thread group name creates foreground thread and foreground threads are ment for executing run method.
  4. Thread group name dispatches (start) the foreground thread to there respective run methods.
  5. Foregrounds threads executes the respective run run methods and gives results to thread group name either all at once or one by one.
  6. Thread group name receives the result from foreground thread either all at once or one by one.
  7. Thread group name gives the result to the java programmer / java application / java application user either all at once or one by one.
  8. Thread group name collects the foreground threads and handoverring to garbage collector.
  9. JVM collects thread the group name and handover to garbage collector.
  10. Java program steps executing because in the java program during the execution.

Write a thread based program for displaying 1 to 10 numbers after each and every second.

// Threaddemo2.java
Class Th1 extends Thread
{
Public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println(“value of i=”+i);
Thread.sleep(1000);
}
}
Catch(InterruptedException ie)
{
System.err.println(“problem in thread execution”);
}
}
}
Class Threaddemo2
{
Public static void main(String args[])
{
Th1 t1=new Th1();
System.out.println(“execution status of t1 before start=”+t1.isAlive());
T1.start();
System.out.println(“execution status of t1 before start=”+t1.isAlive());
try
{
Thread.sleep(5000);
}
Catch(InterruptedException ie)
{
System.out.println(“problem in thread execution”);
}
System.out.println(“execution status of t1 during execution=”+t1.isAlive());
try
{
Thread.sleep(5001);
}
Catch(InterruptedException ie)
{
System.out.println(“problem in thread execution”);
}
System.out.println(“execution status of t1 after completation=”+t1.isAlive());
}
}


Outputexecution status of t1 before start=false //new state
execution status of t1 after start=true //ready state
1
2
3
4
5
6
execution status of t1 during execution=true //running state
7
8
9
10

execution status of t1 after completation=false //halted state

By using java.lang.Runnable interface
Runnable is one of the predefined interface which is containing only one method and whose prototype is given below
Public abstract void run

The run() method of thread class defined with null body and run() method of runnable interface belongs to abstract.


Industry is highly recommended to override abstract run() method of Runnable interface but not recommended to override null body run() method of thread class.

In some of the commencement if one derived class is extending some type of predefined class along with thread class which is not possible because java programming never supports multiple inheritance. To avoid this multiple inheritance problem, rather than extending thread class we implement Runnable interface.

Example 1
Class Th1 extends Applet, Thread //invalid
{
--------
--------
---------
}

Example 2

Class Th1 extends Applet implements Runnable // valid
{
-------
-------
-------
}

Java.lang.Runnable interface is one of the alternative solution for development of Thread based application instead of java.lang.Thread class.
In order to develop any thread based application by using Runnable interface, we chose a class, it must implements java.lang.Runnable interface and override abstract run() method with the logic of the thread.

Class Th1 implements Runnable
{
Public void run()
{
--------
--------
--------
}

Runnable r=new Th1();
r.start();
Runnable t11=new Th1(); //valid
Thread t1=new Thread(t11); //valid
}

Write a java program which will print 1 to 20 no. by using Runnable interface and print the foreground thread name during execution of run() method.
//Threaddemo2.java

class Th1 implements Runnable
{
Thread t11;
Th1()
{
t11=new Thread(this,"rama");
t11.start();
}
public void run()
{
System.out.println("name of FGT in run ()="+t11.getName());
try
{
for(int i=1;i<=20;i++)
{
System.out.println("val of i is="+i);
Thread.sleep(1000);
}
}
catch (InterruptedException ie)
{
System.out.println("problem in thread exectuion");
}
}
}
class ThreadDemo2
{
public static void main(String args[])
{
Th1 t1=new Th1();
}
}


One can also obtain the name of the foreground thread during the execution of run() method by written the following code segment in the run() method.

Example

Public void run()
Thread t11=Thread.currentThread();
System.out.println(“name of FGT into run= ”+t11.getName());

Write a thread based application for computing sum and subtraction of two numbers by making use of thread.

//multhread.java
import java.util.Scanner;
class Sum extends Thread
{
int a,b,c;
void set(int a,int b)
{
this.a=a;
this.b=b;
}
public void run()
{
c=a+b;
System.out.println("sum of"+a+ "and"+b+ "="+c);
}
}
class Sub implements Runnable
{
int a,b,c;
void set(int a,int b)
{
this.a=a;
this.b=b;
}
public void run()
{
c=a-b;
System.out.println("sub of"+a+ "and"+b+ "="+c);
}
}
class MulThread
{
public static void main(String[] args)
{
//accepts the value
Scanner s=new Scanner(System.in);
System.out.println("enter first number");
int x1=Integer.parseInt(s.nextLine());
System.out.println("enter second number");
int x2=Integer.parseInt(s.nextLine());
//create the thread
Sum s1=new Sum();
Sub s2=new Sub();
//setting values
s1.set(x1,x2);
s2.set(x1,x2);
//start the thread
s1.start();
Thread t1=new Thread(s2);
t1.start();
//join the thread
try
{
s1.join();
t1.join();
}
catch(InterruptedException ie)
{
System.out.println("problem in thread exectuion");
}
System.out.println("execution status before join() is="+s1.isAlive());
System.out.println("execution status after join() is="+t1.isAlive());
}
}

In general if we want to perform a no. of independent operation then we need to chose n-number of sub-classes of either thread class or Runnable interface and override the corresponding run() method with the logic related to n no. of independent operation.


Write a Thread-based application for implementing banner animation
Or
Thread implementation for scrolling the given message.


import java.awt.*;
import java.applet.*;
/*<applet code="AppletThread"hight=300,weight=300></applet>*/
public class AppletThread extends Applet implements Runnable
{
String msg="Read java notes by Rama";
public void init()
{
setBackground(Color.yellow);
setForeground(Color.red);
}
public void start()
{
Thread t=new Thread (this);
t.start();
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,50);
g.setFont(f);
g.drawString(msg,100,100);
}
public void run()
{
try
{while(true)
{
char ch=msg.charAt(0);
//msg=msg.subString(1,msg.length());
msg=msg+ch;
Thread.sleep(1000);
repaint();
}//while
}
catch (InterruptedException ie)
{
System.out.println("problem in thread execution");
}
}
}

Thread synchronization

The basic aim of thread synchronization is to generate always consistence results when the thread are executing dependent operation concurrently by eliminating inconsistence results.



Definition :
The mechanism of allowing only one thread , among multiple thread into the sharable area are performing read and write operation for generating consistence results.

Whenever the multiple thread are executing dependent operations then we get inconsistence result by default. To avoid these inconsistent results we apply the concept of thread synchronization.

Need of synchronization let us assume these exist a sharable variable balance and whose initial value is zero. Let us assume there exist two thread t1 and t2 and decided to deposited rupees 10 to 20 in the balance variable respectively both thread started there execution at a time (with the difference of millisecond of time) for depositing rupees 10 and 20 in the balance variable and they completed their execution if we absorb the final value of the balance variable is either 10 or 20 but not 30. Which is one of the inconsistence result.
  • To avoid this inconsistent result we must apply the concept of synchronization
Synchronization technique applied on the above problem

let us assume there exist two threads t1 and t2 and decided to deposit rupees 10 and 20 in the balance variable value. Assume both the thread started there execution at a time with the difference of millisecond of time (t1 started first and later t2 started) then JVM gives values of the balance (0) to the thread t1 and balance variable will be locked at this point of time if thread t2 is trying to access the balance variable value then the thread t2 will be made wait by the JVM until thread t1 complete its execution.

Thread t1 completed its execution and result of the balance variable is 10, balance variable will be unlocked, JVM gives value of the balance variable to whose thread t2 and once again balance variable will be locked.

Thread t2 also completed its execution, balance variable will be unlocked and the final value of the balance variable 30 which is one of the consistence result.

Hence in the synchronization process JVM will continue the process of locking and unlocking until all the thread are completed there execution.
  • Whenever the multiple threads executing independent operation concurrently then we need not to apply synchronization concept because independent operation gives consistence result by default.
  • When multiple threads are executing dependent operations concurrently then by default we get in consistence results. To avoid this consistence results we must apply the concept of synchronization.
Thread Synchronization Technique
In multithreading synchronization techniques are classified into two types they are
  1. Synchronized method
  2. Synchronized blocks
Synchronized methods

If any ordinary method accessed by multiple threads concurrently then the ordinary method generates inconsistence result by default. To eliminate these inconsistence results the definition of ordinary instance method must be made as synchronized by using synchronized keyword based on synchronized keyword we write before the ordinary method they are classified into two types they are,
  1. 1 Synchronized instance method
  2. 2 Synchronized static method
Synchronized instance method

In any ordinary instance method accessed by multiple thread concurrently then we get inconsistence results from ordinary instance method must be made as synchronized by using Synchronized keyword.

Syntax

Synchronized return_type method_name(list of formal parameters type if any)
{
Block of statements;
}

example

class account
{
Private int bal=0;
Synchronized instance method
Synchronized void deposite(int amt)
{
Bal=bal+amt;
System.out.println(“current balance is=”+bal);
}
}


When the thread is executed the above synchronized instance method then JVM locks an object of account class. In general once an ordinary instance method is synchronized then JVM locks an object of corresponding class.

Synchronized static methods

If an ordinary static method accessed by multiple threads then the ordinary static method generates inconsistent results.

To eliminate these inconsistent results the definition of ordinary static method must be made as synchronized by using synchronize keyword.

Syntax

Synchronized static return_type method_name(list of formal parameters types if any)
{
Block of statement;
}

Example
Class Account
{
Private int bal=0;
Synchronized static void deposit(int amt)
{
Bal=bal+amt;
System.out.println(“Current bal= ”+bal);
}
}

In the above example as long as one thread is executing the above synchronized static method then JVM locks the corresponding class called Account in general if any thread executes synchronized static method then JVM locks the corresponding class.

Hence in the synchronization process JVM locks either object or class depends on type of synchronization method executed by JVM

Synchronized Block

It is one of the alternative thread synchronization techniques for eliminating inconsistence results and to get consistence results instead of synchronized method.

Synchronized block always applicable to non-synchronized instance method but not for non- synchronized static method because we always override instance methods but not static methods

Synchronized block always locks object of the corresponding class. Synchronized block must be always return as a part of non-synchronized instance method.

Need of synchronized block

Whenever the derived class inherits non-synchronized instance method either from base class or from base interface and if the inherited non-synchronized instance method accessed by multiple threads then we get in consistence result.

To avoid this inconsistent result, as a derived class programmer we are attempting to write synchronized keyword before the inherited non-synchronized instance method which is not possible because a derived class programmer can’t change the prototype of base class / base interface methods, here we are unable to eliminate the inconsistent result. By using we use the concept of synchronized blocks.

Syntax
Synchronized(object of current class)
{
Block of statements;
}
Package ap;
 Public interface Account
{
Void deposit(int);          //  Public abstract non-synchronized instance method
}
Class SAccount implements Account
{
Public int bal=0; inherited non-synchronized instance method
Public void deposit(int amt)
{
Synchronized(this)
{
bal=bal+amt;
System.out.println(“current bal= ”+bal);
}
Synchronized block
}
}


Write a java program which eliminates the concept of synchronization.
Problem statement : let us assume these exist an account with a variable balance with an initial value zero take two suitable methods for depositing and finding the balance.

Let us assume there exist n number of customers to decided to deposit rupees 10 is in the same account concurrently and insure that consistence result must present in the balance of the account.


// SynchMethd.java
class Account
{
private int bal=0;
void deposit(int amount)
{
bal=bal+amount;
System.out.println("current balance is="+bal);
}
int getBal()
{
return bal;
}
}
class Cust extends Thread
{
Account ac;
Cust( Account ac)
{
this.ac=ac;
}
public void run()
{
ac.deposit(10);
}
}
class SynchMethd
{
public static void main(String[] args)
{
Account ac=new Account();
//create the array of customer object
Cust cu[]=new Cust[10];
//give single object of A/C class to array of coustomer thread
for(int i=0;i<10;i++)
{
cu[i]=new Cust(ac);
}
//start the customer thread for depending rs10/-in the balance variable
for(int i=0;i<10;i++)
{
cu[i].start();
}
//join the array of customer thread
try
{
for(int i=0;i<10;i++)
{
cu[i].join();
}
}
catch(InterruptedException ie)
{
System.out.println("exception in thread execution");
}
System.out.println("total balance is="+ac.getBal());
}
}

Note 1:
If we run any synchronization based application on mono / single user operation system (dos, window 98) then it is mandatory to the java programmer to write synchronized keyword whenever it is required because mono OS’s does not contain implementation of synchronization concept. If we don’t write synchronized keyword then we get inconsistent result.

Note 2:


If we run any synchronization based application on multiuser / multithreaded OS’s (windows 95, window xp, linux, unix etc). Then it is optional to the java programmer to write synchronized keyword because multithreaded OS’s contains in build synchronization implementation. If we depends on OS based synchronization then we get consistency in the final result and order of updation may or may not be consistent

Note 3:

Industry is always recommended to write synchronized keyword whenever synchronized concept is available or making the java application to execute on every OS and to give consistency in the final result and consistency in the order of updation.

Interthread communication:


  • Interthread communication of java is one of the specialized form of inter process communication of OS
  • Interthread communication based application and very faster application compared to all application in the real world.

Real time implementations of Interthread communication
  • Interthread communication can be used as a development of universal protocols.
  • Interthread communication can be used in the development of universal server software development.
Definition
  • The process of execution of exchanging of the data / information between multiple threads is known as Interthread communication or if an output of first thread giving as an input to second thread the output of second thread giving as an input to third thread then the communication between first second and third thread known as Interthread communication.
  • In order to develop Interthread communication application we use some of the methods of java.lang.Object class and these methods are known as Interthread communication methods.


Methods in java.lang.Object(Interthread communication methods)
  1.  Public final void wait (long msec) throws  java.lang.InterruptedException
  2. Public final void wait ()
  3. Public final void notify()
  4. Public final void notifyAll()
  • Method "Public final void wait (long msec)" is used for making the thread to wait by specifying the waiting time in terms of milliseconds. Once the waiting time is completed, automatically the thread will be interred into ready state from waiting state.

This methods is not recommended to used to make next thread to wait on the basis of time because java programmer may not be able to decide or determine the CPU burst time of current thread and CPU burst time is decided by OS but not by the programmer.
  • Methods "Public final void wait ()" is used for making the thread to wait without specifying any waiting time this method is recommended to use to make the next thread to wait until current thread complete its execution.

Programmatically it will decide whether current thread is completed or not.
  • Method "Public final void notify()" is used for transferring one thread at a time from waiting state to ready state.
  • Method "Public final void notifyAll()" is used for transferring all the threads at a time from waiting state to ready state.
  • Method "Public final void wait (long msec)" and "Public final void wait ()" throws a predefined Exception called java.lang.InterruptedException. (for more explanation see the method sleep previous page)

Classical examples of interthread communication
(1) Producer consumer problem
(2) Dinning philosopher problem
(3) Reading writing problem
(4) Burber shop problem

Producer consumer problem
Producer

Producer id one of the thread which will produce the items which are consumed be consumer. At any point of time produce the thread produced one value at a time.

Consumer
Consumer is one of the thread which will consumer the times which are produced by producer consumer thread will consume only one item at a time but not multiple items I

The following diagram gives implements for producer consumer problem.



class Q
{
boolean valSet=false;
int n;
synchronized void put(int i)
{
try
{
if(valSet)
{
wait();
}
}
catch (InterruptedException ie)
{
System.out.println("problem in thread exceution");
}
n=i;
System.out.println("put="+n);
valSet=true;
notify();
}
synchronized int get()
{
try
{
if(!valSet)
{
wait();
}
}
catch (InterruptedException ie)
{
System.out.println("problem in thread exceution");
}
System.out.println("got="+n);
valSet=false;
notify();
return(n);
}//put()
}//Q
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
Thread t1=new Thread(this);
t1.start();
}
public void run()
{
int i=0;
while(true)
{
q.put(++i);
}
}
}//producer
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
Thread t1=new Thread(this);
t1.start();
}
public void run()
{
while(true)
{
int x=q.get();
}
}
}//producer
class ProdConsDemo
{
public static void main(String[] args)
{
Q q=new Q();
Producer po=new Producer(q);
Consumer co=new Consumer(q);
}
}

Output
C:/>javac PcDemo.java

C:/>java PcDemo

Put = 1

Get = 1

Put = 2

Get = 2

--------
--------
--------

Lear more about Multithreading in Java