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

CH2-Multithreading

Unit 2 covers the concept of multithreading in Java, explaining that a thread is a lightweight process that allows for concurrent execution of tasks. It discusses the lifecycle of a thread, methods for creating threads, and the importance of synchronization to prevent data corruption when multiple threads access shared resources. Additionally, it highlights various thread management techniques such as thread priorities, yielding, joining, and sleeping.

Uploaded by

shankarranbavle6
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)
12 views

CH2-Multithreading

Unit 2 covers the concept of multithreading in Java, explaining that a thread is a lightweight process that allows for concurrent execution of tasks. It discusses the lifecycle of a thread, methods for creating threads, and the importance of synchronization to prevent data corruption when multiple threads access shared resources. Additionally, it highlights various thread management techniques such as thread priorities, yielding, joining, and sleeping.

Uploaded by

shankarranbavle6
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/ 15

Unit 2: Multithreading

 A thread represents a separate path of execution of a group of statements.

Program:
class Current
{
public static void main(String [] args)
{
System.out.println(" Check the current Thread:");
Thread t= Thread.currentThread();
System.out.println("Current Thread : "+t);
System.out.println(" Thread Name :" + t.getName());
}
}

Def.: A program can be divided into a number of small processes. Each small
process can be addressed as a single thread (a lightweight process).
OR
A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.
 In order to perform complicated tasks in the background, Thread concept was introduced in Java.
 All the tasks are executed without affecting the main program.
 In a program or process, all the threads have their own separate path for execution, so each thread of a
process is independent.
 Another benefit of using thread is that if a thread gets an exception or an error at the time of its
execution, it doesn't affect the execution of the other threads.
 All the threads share a common memory and have their own stack, local variables and program
counter.
 When multiple threads are executed in parallel at the same time, this process is known
as Multithreading.
 Multithreaded programs contain two or more threads that can run concurrently and each thread
defines a separate path of execution. This means that a single program can perform two or more tasks
simultaneously.
 For example, one thread is writing content on a file at the same time another thread is performing
spelling check.

Why use Threads in Java?


The Java run-time system depends on threads for many things. Threads reduce inefficiency by preventing
the waste of CPU cycles.

Why Multithreading?
The thread has many advantages over the process to perform multitasking. The process is heavy, takes
more memory, and occupiesthe CPU for a longer time which may lead to performance issues with the
system. To overcome this issue process is broken into small units of independent sub-processes. These
sub-processes are called threads that can perform independent tasks efficiently. So nowadays computer
systems prefer to use thread over the process and use multithreading to perform multitasking.
Main Thread:
 When we run any java program, the program begins to execute its code starting from the main
method. Therefore, the JVM creates a thread to start executing the code present in main method. This
thread is called as main thread.
 Although the main thread is automatically created, you can control it by obtaining a reference to it by
calling currentThread() method.
 Two important things to know about main thread are:
o It is the thread from which other threads will be produced.
o It must be always the last thread to finish execution

Life cycle of a Thread


1) New: The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable(Blocked): This is the state when the thread is still alive, but is currently not eligible
to run.
5) Terminated: A thread is in terminated or dead state when its run() method exits.

How to Create a Java Thread


Java lets you create thread in following two ways:-
1. By extending the Thread
2. By implementing the Runnable interface.

EXTENDING THREAD CLASS


The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the
code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using
the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the
thread eligible for running.

PROGRAM1:
class MultithreadingDemo extends Thread
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemoobj=new MultithreadingDemo();
obj.start();
}
}

PROGRAM:
class MyThread extends Thread {
public void run() {
for(inti=1;i<=10;i++)
System.out.println("Child Thread");
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread T1 = new MyThread();
T1.start();
for(inti=1;i<=10;i++)
System.out.println("Main Thread");
}
}
A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is
in the runnable state.

IMPLEMENTING THE RUNNABLE INTERFACE


The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the
Thread constructor. The Thread object now has a Runnable object that implements the
run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start()
method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an
uncaught exception

PROGRAM 2:
class MultithreadingDemo1 implements Runnable
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemoobj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Important methods of Thread class
Method Description
setName() To give thread a name
getName() Return thread's name
getPriority() Return thread's priority
isAlive() Checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() Suspend thread for a specified time
start() Start a thread by calling run() method
activeCount() Returns an estimate of the number of active threads in the current
thread's thread group and its subgroups.
checkAccess() Determines if the currently running thread has permission to
modify this thread.
currentThread() Returns a reference to the currently executing thread object.
getId() Returns the identifier of this Thread.
getState() Returns the state of this thread.
interrupt() Interrupts this thread.
isAlive() Tests if this thread is alive.
isDaemon() Tests if this thread is a daemon thread.
isInterrupted() Tests whether this thread has been interrupted.
setPriority(intnewPriority) Changes the priority of this thread.
yield() A hint to the scheduler that the current thread is willing to yield
its current use of a processor.

EXAMPLE:
class Current
{
public static void main(String [] args)
{
System.out.println(" Check the current Thread:");
Thread t= Thread.currentThread();
System.out.println("Current Thread : "+t);
System.out.println(" Thread Name :" + t.getName());
System.out.println(" Thread ID :" + t.getId());
System.out.println(" Thread State :" + t.getState());
System.out.println(" Thread Active Count:" + Thread.activeCount());
System.out.println(" Thread Priority:" + t.getPriority());
System.out.println(" Thread isAlive:" + t.isAlive());
System.out.println(" Thread isDaemon:" + t.isDaemon());
System.out.println(" Thread isInturrupted:" + t.isInterrupted());
}
}
Thread Constructors
 Thread T1=new Thread();
 Thread T1=new Thread(Runnable obj);
 Thread T1=new Thread(String name);
 Thread T1=new Thread(Runnable obj, String name);
 Thread T1=new Thread(ThreadGroup grp, String name);
 Thread T1=new Thread(ThreadGroup grp, Runnable obj);
 Thread T1=new Thread(ThreadGroup grp, Runnable obj, String name);
 Thread T1=new Thread(ThreadGroup grp, Runnable obj, String name, long stacksize) ;

Every thread in JAVA has some name, default name generated by JVM or customized
name provided by programmer.

WE can get and set thread name by using methods setName() and getName()

EXAMPLE:
class MyThread extends Thread {
public void run() {

}
}

public class ThreadDemo1 {

public static void main(String[] args) {


System.out.println("Main Thread name:"+Thread.currentThread().getName());
MyThread T1=new MyThread();
System.out.println("T1 Thread name:"+T1.getName());
//Cahnging Main thread name
Thread.currentThread().setName("ThreadDemoProg");
System.out.println("Main Thread name:"+Thread.currentThread().getName());
//Changing name of T1 thread
T1.setName("Thread-T1");
System.out.println("T1 Thread name:"+T1.getName());
}
}

Thread.currentThread Method:
We can get current running executing thread by Thread.currentThread() method.

EXAMPLE:
class MyThread extends Thread {
public void run() {
System.out.println("Run executed by:"+Thread.currentThread().getName());
}
}

public class currentThreadMethodDemo {


public static void main(String[] args)
{ MyThread T1=new MyThread();
T1.start();
System.out.println("Main executed by:"+Thread.currentThread().getName());

}
}

Thread Priorities:
 Each thread have a priority. Priorities are represented by a number between 1 and 10.
 Three constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
 Thread class defines following methods to get and set priorities of thread
public final intgetPriority();
public final void setPriority(int);
 For setPriority() method allowed range of values is 1 to 10 otherwise it will raise
IllegalArgumentException will be raised.
 Default priority for every child thread is inherited from parent thread.
 The Main thread has default priority as 5 i.e. Thread.NORM_PRIORITY

class MyThread extends Thread {


public void run() {
for(inti=1;i<=10;i++)
System.out.println("Child Thread");
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) {
MyThread T1 = new MyThread();
T1.setPriority(10);
T1.start();
for(inti=1;i<=10;i++)
System.out.println("Main Thread");
}
}

Note: Some platform won’t provide support for priorities.

Multiple Thread Execution:Controlling Thread Execution


 We can prevent thread execution by using yield(), join() and sleep() methods.
 Yield() method :
o yield() causes to pauses current executing thread to give the chance for the waiting threads of
same priority or high priority.
o If no waiting thread or all waiting threads have low priority then same thread can continue its
execution.
o The thread which executes the yield method will enter in the Runnable state from Running
state.
o If multiple threads are waiting with same priority then which waiting thread will get the
chance to execute it depends on thread scheduler.
o The thread which is yielded when it will get chance to execute it depends on thread scheduler.
public static native void yield();
Note: Some platform won’t provide support for priorities.
class MyThread extends Thread {
public void run() {
for(inti=1;i<=10;i++)
{System.out.println("Child Thread");
Thread.yield();
}
}
}

public class ThreadYieldDemo {


public static void main(String[] args) {
MyThread T1 = new MyThread();
T1.start();
for(inti=1;i<=10;i++)
System.out.println("Main Thread");
}
}

When T1 threads gets chance to execute it pauses and gives chance to execute Main thread

 join() Method:
o The join() method of a Thread instance is used to join the start of a thread’s execution to the
end of another thread’s execution such that a thread does not start running until another
thread ends.
o If join() is called on a Thread instance, the currently running thread will block until the
Thread instance has finished executing.
o Consider T1 and T2 threads,
 if T1 wants to wait until T2 completes then T1 has to call T2.join().
 when T1 executes T2.join(), T1 enters into waiting state until T2 completes its
execution.
 Once T2 completes then T1 can continue its execution.
o EX: considers T1: ResultPrinting T2:NameCorrection are the threads, here also T1 needs to
call T2.join as T1 can continue its execution after until T2 completes execution.
o Syntax: public final void join()
o Every join method throws InterruptedException
 sleep() Method
o This method causes the currently executing thread to sleep for the specified number of
milliseconds.
o The method sleep() is being used to halt the working of a thread for a given amount of time.
o The time up to which the thread remains in the sleeping state is known as the sleeping time of
the thread.
o After the sleeping time is over, the thread starts its execution from where it has left.
o
 public static void sleep(long mls) throws InterruptedException
 public static void sleep(long mls, int n) throws InterruptedException
o Whenever another thread does interruption while the current thread is already in the sleep
mode, then the InterruptedException is thrown.
o Thread.sleep() method can be used with any thread. It means any other thread or the main
thread can invoke the sleep() method.
o EXAMPLE:
class MyThread extends Thread {
public void run()
{
try
{
for(inti=1;i<=10;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{System.out.println("InterruptedException");
}
}
}

public class ThreadSleepDemo {


public static void main(String[] args) {
MyThread T1 = new MyThread();
MyThread T2 = new MyThread();
MyThread T3 = new MyThread();
T1.start();
T2.start();
T3.start();
//T1.join();
for(inti=1;i<=10;i++)
System.out.println("Main Thread :"+ i);
}
}

SETA 1,2

The thread can interrupt a sleeping thread or waiting thread by using interrupt() method

Synchronization:
 In Java multiple threads runs parallel to complete their execution.
 We need to synchronize the shared resources to ensure that at a time only one thread is able to access
the shared resource.
 If an Object is shared by multiple threads then there is need of synchronization in order to avoid the
Object’s state to be getting corrupted.
 Synchronization is needed when Object is mutable. If shared Object is immutable or all the
threads which share the same Object are only reading the Object’s state not modifying then you don’t
need to synchronize it.
 Java programming language provide two synchronization idioms:
o Methods synchronization
o Statement(s) synchronization (Block synchronization)

Method Synchronization:
 Synchronized methods prevents the thread interference and memory consistency errors.
 If an Object is visible to more than one threads, all reads or writes to that Object’s fields are done
through the synchronized method.
 It is not possible for two invocations for synchronized methods to interleave.
 If one thread is executing the synchronized method, all others thread that invoke synchronized
method on the same Object will have to wait until first thread is done with the Object.
EXAMPLE:

class MyThreadTable extends Thread


{
intnum;
public MyThreadTable(int n)
{num=n;}

public void run()


{
this.printTable();
}
synchronized void printTable()
{
for(inti=1;i<=10;i++)
System.out.println(i*num);
}

class TestMyThreadTable
{
public static void main(String [] args)
{
MyThreadTable T1 = new MyThreadTable (5);
MyThreadTable T2 = new MyThreadTable (8);
T1.start();
T2.start();
}
}
Block Synchronization:
 If we only need to execute some subsequent lines of code not all lines (instructions) of code within a
method, then we should synchronize only block of the code within which required instructions are
exists.
 For example, lets suppose there is a method that contains 100 lines of code but there are only 10 lines
(one after one) of code which contain critical section of code i.e. these lines can modify (change) the
Object’s state. So we only need to synchronize these 10 lines of code method to avoid any
modification in state of the Object and to ensure that other threads can execute rest of the lines within
the same method without any interruption.
EXAMPLE:

class SyncBlock extends Thread


{
public void run()
{
this.Display();
}

void Display()
{
for(inti=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+i+"Before Sync. Block");

synchronized(this)
{
for(inti=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+i+"In Sync. Block");
}

for(inti=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+i+"After Sync. Block");
}
}

class TestSyncBlock
{
public static void main(String [] args)
{
SyncBlock T1 = new SyncBlock ();
SyncBlock T2 = new SyncBlock ();
T1.start();
T2.start();
}
}
Inter Thread Communication in Java
 Inter-thread communication in Java is a technique through which multiple threads communicate with
each other
 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 in Java can be achieved by using three methods
1. wait() 2. notify() 3. notifyAll()
 Note-These methods can be called only from within a synchronized method or synchronized
block of code
 To call wait(), notify(), notifyAll() in any object thread should be owner of that object (i.e thread
should have lock on the object) so wait, notify and notifyAll from synchronized area otherwise we
will get runtime exception IllegalMonitorException
 wait():
o If thread calls wait() method on any object it immediately releases lock of that particular
object and enters into waiting state.
o calling wait() forces the current thread to wait until some other thread
invokes notify() or notifyAll() on the same object.
 notify(): if thread calls notify method on any object it releases lock of that object but may not
immediately. except wait, notify and notifyAll there is no other method where thread releases lock.
EXAMPLE:
/*Write a java program for to solve producer consumer problem in which a producer produce a value and
consumer consume the value before producer generate the next value.*/

class Buffer
{
int value;
boolean produced=false;
public synchronized void produce(int x)
{
if(produced)
{ try
{
wait();
}
catch(Exception e)
{ System.out.println(e); }
}
value=x;
System.out.println(value+"is produced");
produced=true;
notify();
}

public synchronized void consume()


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

class Producer extends Thread


{
Buffer buffer;
public Producer(Buffer b)
{
buffer =b;
}
public void run()
{
System.out.println("Producer started producing value........");
for(inti=1;i<=10;i++)
buffer.produce(i);
}
}

class Consumer extends Thread


{
Buffer buffer;
public Consumer(Buffer b)
{
buffer =b;
}
public void run()
{
System.out.println("Consumer started consuming value.......");
for(inti=1;i<=10;i++)
buffer.consume();
}
}

class ProducerConsumer
{
public static void main(String arr[])
{
Buffer b=new Buffer();
Producer p=new Producer(b);
Consumer c=new Consumer(b);
p.start();
c.start();
}
}

---------------xxxxxxxxxxxxx--------------

You might also like