0% found this document useful (0 votes)
79 views

Multi Threading (1)

Uploaded by

dornalankitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Multi Threading (1)

Uploaded by

dornalankitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

MultiThreading

Information about multithreading:-


1) The earlier days the computer’s memory is occupied only one program after completion of
one program it is possible to execute another program is called uni programming.
2) Whenever one program execution is completed then only second program execution will
be started such type of execution is called co operative execution, this execution we are
having lot of disadvantages.
a. Most of the times memory will be wasted.
b. CPU utilization will be reduced because only program allow executing at a time.
c. The program queue is developed on the basis co operative execution
To overcome above problem a new programming style will be introduced is called
multiprogramming.
1) Multiprogramming means executing the more than one program at a time.
2) All these programs are controlled by the CPU scheduler.
3) CPU scheduler will allocate a particular time period for each and every program.
4) Executing several programs simultaneously is called multiprogramming.
5) In multiprogramming a program can be entered in different states.
a. Ready state. b. Running state. c. Waiting state.
6) Multiprogramming mainly focuses on the number of programs.
Advantages of multiprogramming:-
1. CPU utilization will be increased.
2. Execution speed will be increased and response time will be decreased.
3. CPU resources are not wasted.
Thread:-
1) Thread is nothing but separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program executed simultaneously that each and
every part is called thread.
4) The thread is light weight process because whenever we are creating thread it is not
occupying the separate memory it uses the same memory. Whenever the memory is
shared means it is not consuming more memory.
5) Executing more than one thread a time is called multithreading
Single threaded model:-
class Test
{ //begins
public static void main(String[] args)
{
System.out.println("Hello World!");
System.out.println("hi ram"); // body
System.out.println("hello CSE");
}
} //end
In the above program only one thread is available is called main thread to know the name of
the thread we have to execute the fallowing code.
class Test
{
public static void main(String[] args)
{
System.out.println("Hello World!");
Thread t=Thread.currentThread();
System.out.println("currrent thread information is : "+t);//[main,5,main]
System.out.println("currrent thread priority is : "+t.getPriority());//5
System.out.println("currrent thread name is : "+t.getName());
System.out.println("hi ram");
System.out.println("hello CSE");
}
}
In the above program only one thread is available name of that thread is main thread.
Step 3:-
Starts the execution of a thread.
t.start();
In this approach take one user defined class class that is extending Thread class .
Ex:-
class MyThread extends Thread
{
public void run()
{
System.out.println("MREC from CSE");
System.out.println("body of the thread");
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}
Note :-
1) Whenever we are calling t.start() method the JVM search for the start() in the MyThread
class but the start() method is not present in the MyThread class so JVM goes to parent class
called Thread class and search for the start() method.
2) In the Thread class start() method is available hence JVM is executing start() method.
3) Whenever the thread class start() that start() is responsible person to call run() method.
4) Finally the run() automatically executed whenever we are calling start() method.
5) Whenever we are giving a chance to the Thread class start() method then only a new
thread will be created.
Life cycle stages are:-
1) New
2) Ready
3) Running state
4) Blocked / waiting / non-running mode
5) Dead state
New :-
MyThread t=new MyThread();
Ready :-
t.start()
Running state:-
If thread scheduler allocates CPU for particular thread. Thread goes to running state

The Thread is running state means the run() is executed.


Blocked State:-
If the running thread got interrupted of goes to sleeping state at that moment it goes to the
blocked state.
Dead State:-
If the business logic of the project is completed means run() over thread goes dead state.
Second approach to create thread implementing Runnable interface:-
Step 1:-
Creates a class that implements Runnable interface.
class MyClass extends Runnable
{
public void run()
{
System.out.println("MREC from CSE");
System.out.println("body of the thread");
}
};
Step 2:-
Creating a object.
MyClass obj=new MyClass();
Step 3:-
Creates a Thread class object.
Thread t=new Thread(obj);
Step 4:-
Starts the execution of a thread.
t.start();
implementing Runnable interface
class MyThread implements Runnable
{
public void run()
{
System.out.println("mrec from cse");
System.out.println("body of the thread");
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyClasss obj=new MyClass();
Thread t=new Thread(obj);
t.start();
}
}
Step 1:-
the Class MyClass implements the Runnable interface and overriding run() method and
contains
the logic associates with the body of the thread.
Step 2:-
Creates the object of implementation class this is not like a first mechanism.
Step 3 :-
Creates a generic thread object then pass the MyClass reference variable as a parameter to
that
object.
Step 4:-
As a result of third step 3 a thread object is created in order to execute this thread method we
need to class start() method. Then new thread is executed.
We are having two approaches:-
First approach:-
1) By extending the thread class, the derived class itself is a thread object and it gains full
control over the thread life cycle.
2) Another important point is that when extending the Thread class, the sub class cannot
extend
any other base classes because Java allows only single inheritance.
if the program needs a full control over the thread life cycle, then extending the Thread class
is a good choice.
Second approach:-
1) Implementing the Runnable interface does not give developers any control over the thread
itself, as it simply defines the unit of work that will be executed in a thread.
2) By implementing the Runnable interface, the class can still extend other base classes if
necessary.
if the program needs more flexibility of extending other base classes, implementing the
Runnable interface would be preferable.
We are having two approaches two create a thread use any approach based on application
requirement.
Particular task is performed by the number of threads:-
1) Particular task is performed by the number of threads here number of threads(t1,t2,t3) are
executing same method (functionality).
2) In the above scenario for each and every thread one stack is created. Each and every
method called by particular Thread the every entry stored in the particular thread stack.
Here Four Stacks are created
Main -----------stack1
t1---------------stack2
t2--------------stack3
t3-------------stack4
class MyThread extends Thread
{
public void run()
{
System.out.println("cse");
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}
Ex5:-multiple threads are performing multiple operation.
class MyThread1 extends Thread
{
public void run()
{
System.out.println("mythread1 task");
}
}
class MyThread2 extends Thread
{
public void run()
{
System.out.println("mythread2 task");
}
}
class MyThread3 extends Thread
{
public void run()
{
System.out.println("Mythread3 task");
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
t1.start();
t2.start();
t3.start();
}
}
class RamThread extends Thread
{
public void run()
{
System.out.println("Enter into thread Ram");
System.out.println("thread Ram is started");
for (int i=0;i<10 ;i++ )
{
System.out.println("Ram");
}
System.out.println("thread Ram is ended");
}
}
class NagThread extends Thread
{
public void run()
{
System.out.println("Enter into thread Nag");
System.out.println("thread Nag is started");
for (int i=0;i<10 ;i++ )
{
System.out.println("Nag");
}
System.out.println("thread Nag is ended");
}
};
class RamaThread extends Thread
{
public void run()
{
System.out.println("Enter into thread Rama");
System.out.println("thread Rama is started");
for (int i=0;i<10 ;i++ )
{
System.out.println("Rama");
}
System.out.println("thread Rama is ended");
}
};
class ThreadDemo
{
public static void main(String[] durga)
{
RamThread thread1=new RamThread();
NagThread thread2=new NagThread();
RamaThread thread3=new RamaThread();
thread1.setPriority(Thread.MAX_PRIORITY);
System.out.println(thread1.getPriority());
Thread2.setPriority(Thread.MIN_PRIORITY);
System.out.println(thread2.getPriority());
Thread3.setPriority(thread2.getPriority()+1);
System.out.println(thread3.getPriority());
System.out.println("starting of RamThread");
thread1.start();
System.out.println("starting of Nag Thread");
thread2.start();
System.out.println("starting of Rama Thread");
thread3.start();
}
};

Some of the thread class methods:-


Sleep():-
The sleep()method causes the current thread to sleep for a specified amount of time in
milliseconds.
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis,int nanosec) throws InterruptedException
For example, the code below puts the thread in sleep state for 5 minutes:
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
for (int i=0;i<10 ;i++)
{
System.out.println("Ram");
Thread.sleep(5*1000);//5 seconds
Thread.sleep(5*60*1000);// 5 minits
}
}
catch (InterruptedException ie)
{
System.out.println("the thread is got innterupted");
}
}
}
Ex :-
class Test
{
public static void main(String[] args)throws InterruptedException
{
System.out.println("Ram");
Thread.sleep(3*1000);
}
}
Ex:-
class MyThread extends Thread
{
public void run()
{
for (int i=0;i<5;i++ )
{
try{
System.out.println("ram");
Thread.sleep(3*1000);}
catch(InterruptedException iee)
{
System.out.println("gettting innterupted exctpion");
}
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
try
{
t1.join();
}
catch (InterruptedException ie)
{
System.out.println("interrupted Exception");
}
t2.start();
}
};
Ex 2:-
class MyThread extends Thread
{
public void run()
{
for (int i=0;i<5;i++ )
{
try{
System.out.println("ram");
Thread.sleep(3*1000);}
catch(InterruptedException ie)
{
System.out.println("getting excception");
}
}
}
}
class ThreadDemo
{
public static void main(String[] args)throws InterruptedException
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t1.join();
t2.start();
}
};
isAlive():-
used to check whether the thread is live or not.
Public Boolean isAlive()
class MyThread extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
System.out.println(t.isAlive());
t.start();
System.out.println(t.isAlive());
}
};

Java.lang.Thread.activeCount():-
This method is used to find out the number of methods in active state.
Public static int activeCount();
Ex:-
class MyThread extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
System.out.println(Thread.activeCount());//4
}
};
Java.lang.currentThread():-
This method is used to represent current thread class object.
Public static thread currentThread()
Ex:-
class MyThread extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
};
Java.lang.Thread.getId():-
getId() is used to generate id value for each and every thread.
Public long getId()
Ex:-
class MyThread extends Thread
{
public void run()
{
System.out.println(" rattaiah thread is running ");
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println("the thread id :"+t1.getId());
System.out.println("the thread name is :"+t1.getName());
System.out.println("the thread priority is "+t1.getPriority());
System.out.println("the thread id :"+t2.getId());
System.out.println("the thread name is :"+t2.getName());
System.out.println("the thread priority is "+t2.getPriority());
}
};
Interrupted():-
A thread can interrupt another sleeping or waiting thread.
For this Thread class defines interrupt() method.
Public void interrupt()
Effect of interrupt() method call:-
class MyThread extends Thread
{
public void run()
{
try
{
for (int i=0;i<10;i++ )
{
System.out.println("i am sleeping ");
Thread.sleep(5000);
}
}
catch (InterruptedException ie)
{
System.out.println("i got interupted by interrupt() call");
}
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
t.interrupt();
}
};
No effect of interrupt() call:-
class MyThread extends Thread
{
public void run()
{
for (int i=0;i<10;i++ )
{
System.out.println("i am sleeping ");
}
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
t.interrupt();
}
};

NOTE:-
The interrupt() is working good whenever our thread enters into waiting state or
sleeping state.
The interrupted call will be wasted if our thread doesn’t enters into the waiting/sleeping
state.
class MyThread extends Thread
{
public void run()
{
for (int i=0;i<10;i++)
{
Thread.sleep(2000);
System.out.println("CSE");
}
}
};
class ThreadDemo
{
public static void main(String[] args)throws Exception
{
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
t1.start();
t2.start();
t3.start();//4-threads
t1.join();
System.out.println(t1.getName());//thread-0
System.out.println(t2.getName());
System.out.println(t3.getName());
t1.setName("sneha");
System.out.println(t1.getName());//sneha
System.out.println(Thread.currentThread().getName());//main
Thread.currentThread().setName("poornima");
System.out.println(Thread.currentThread().getName());//poornima
System.out.println(Thread.activeCount());
System.out.println(t1.isAlive());
System.out.println(t1.getId());
System.out.println(t2.getId());
System.out.println(Thread.currentThread().getPriority());
System.out.println(t1.getPriority());
Thread.currentThread().setPriority(10);
System.out.println(Thread.currentThread().getPriority());
for (int i=0;i<5;i++)
{
Thread.sleep(5000);
Thread.yield();
System.out.println("main thread");
}
}
};
Difference between Process and Thread

The following table highlights the major differences between a process and a thread −

Comparison
Process Thread
Basis

Definition A process is a program under A thread is a lightweight process


execution i.e. an active program. that can be managed
independently by a scheduler

Context Processes require more time for Threads require less time for
switching time context switching as they are context switching as they are
heavier. lighter than processes.

Memory Sharing Processes are totally A thread may share some memory
independent and don’t share with its peer threads.
memory.

Communication Communication between Communication between threads


processes requires more time requires less time than between
than between threads. processes.
Blocked If a process gets blocked, If a user level thread gets blocked,
remaining processes can all of its peer threads also get
continue execution. blocked.

Resource Processes require more Threads generally need less


Consumption resources than threads. resources than processes.

Dependency Individual processes are Threads are parts of a process and


independent of each other. so are dependent.

Data and Code Processes have independent data A thread shares the data segment,
sharing and code segments. code segment, files etc. with its
peer threads.

Treatment by OS All the different processes are All user level peer threads are
treated separately by the treated as a single task by the
operating system. operating system.

Time for creation Processes require more time for Threads require less time for
creation. creation.

Time for Processes require more time for Threads require less time for
termination termination. termination.

Inter-thread communication:
Inter-thread communication in Java is a technique through which multiple threads
communicate with each other.

It provides an efficient way through which more than one thread communicate with each
other by reducing CPU idle time. CPU idle time is a process in which CPU cycles are not
wasted.

When more than one threads are executing simultaneously, sometimes they need to
communicate with each other by exchanging information with each other. A thread
exchanges information before or after it changes its state.

There are several situations where communication between threads is important.

For example, suppose that there are two threads A and B. Thread B uses data produced by
Thread A and performs its task.
If Thread B waits for Thread A to produce data, it will waste many CPU cycles. But if
threads A and B communicate with each other when they have completed their tasks, they do
not have to wait and check each other’s status every time.
Inter-thread communication is a process in which a thread is paused running in its critical
region and another thread is allowed to enter (or lock) in the same critical region to be
executed. i.e. synchronized threads communicate with each other.
Below object class methods are used for Inter-thread communication process:
1. wait(): this method instructs the current thread to release the monitor held by it and to get
suspended until some other threads sends a notification from the same monitor.

Syntax: public void wait() throws InterruptedException.

2. notify(): this method is used to send the notification to the thread that is suspended by the
wait() method.

Syntax: public void notify().

3. notifyAll(): this method is used to send the notification to all the threads that are suspended
by wait() method.
Syntax: public void notifyAll().

Producer-consumer problem to understand Inter-thread communication.


class Buffer{
int a;
boolean produced = false;

public synchronized void produce(int x){


if(produced){
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
a=x;
System.out.println("Product" + a + " is produced.");
produced = true;
notify();
}

public synchronized void consume(){


if(!produced){
System.out.println("Consumer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
System.out.println("Product" + a + " is consumed.");
produced = false;
notify();
}
}

class Producer extends Thread{


Buffer b;
public Producer(Buffer b){
this.b = b;
}

public void run(){


System.out.println("Producer start producing...");
for(int i = 1; i <= 10; i++){
b.produce(i);
}
}
}

class Consumer extends Thread{


Buffer b;
public Consumer(Buffer b){
this.b = b;
}

public void run(){


System.out.println("Consumer start consuming...");
for(int i = 1; i <= 10; i++){
b.consume();
}
}
}

public class ProducerConsumerExample {


public static void main(String args[]){
//Create Buffer object.
Buffer b = new Buffer();
//creating producer thread.
Producer p = new Producer(b);

//creating consumer thread.


Consumer c = new Consumer(b);

//starting threads.
p.start();
c.start();
}
}

You might also like