0% found this document useful (0 votes)
26 views17 pages

Unit-6 Multithreading (E-Next - In)

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)
26 views17 pages

Unit-6 Multithreading (E-Next - In)

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

Unit-6 Multi-threading

Q.1 Explain thread life cycle in detail. Write a program to create two threads (inter thread
communications).
Q.2 What is thread? Explain thread life cycle in detail.
Q.3 How the thread is created? Draw the life cycle of thread.
Q.4 Write a program to demonstrate the thread life cycle.
Thread in Java:
 A thread is a lightweight sub process, a smallest unit of processing. It is a separate
path of execution.
 Each thread has its own local variables, program counter and lifetime.
 Threads are independent, if there occurs exception in one thread, it doesn’t affect
other threads.
 It shares a common memory area.
 Thread is executed inside the process.
 There is context-switching between the threads.
 There can be multiple processes inside the OS and one process can have multiple
threads.

Life cycle of a Thread (Thread States):


 A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
 But for better understanding the threads, we are explaining it in the 5 states.

Life cycle of a Thread (Thread States)

Khan S. Alam 1 [Link]


Unit-6 Multi-threading

The life cycle of the thread in java is controlled by JVM.


The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New
 The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
 A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 public static final [Link] NEW

2) Runnable
 The thread is in runnable state after invocation of start() method.
 A thread that is ready to run is moved to runnable state.
 In this state, a thread might actually be running or it might be ready run at any
instant of time.
 It is the responsibility of the thread scheduler to give the thread, time to run.
 A thread in this state is considered to be executing its task.
 public static final [Link] RUNNABLE

3) Running
 The thread is in running state if the thread scheduler has selected it.
 public static final [Link] Running

4) Non-Runnable (Blocked/Waiting)
 This is the state when the thread is still alive, but is currently not eligible to run.
 When a thread is temporarily inactive, then it’s in one of the following states:
1. Blocked
2. Waiting
 public static final [Link] BLOCKED
 public static final [Link] Time_Wait

5) Terminated
 A thread is in terminated or dead state when its run() method exits and it’s no longer
in use.
 A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
 public static final [Link] TERMINATED

Khan S. Alam 2 [Link]


Unit-6 Multi-threading

Example to illustrate the life-cycle of the thread:

public class ThreadDemo extends Thread


{
public void run()
{
[Link] ("Thread is running !!");
}

public static void main (String[] args)


{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();

[Link] ("T1 ==> "+ [Link]());


[Link] ("T2 ==> "+ [Link]());
[Link]();

[Link] ("T1 ==> "+ [Link]());


[Link] ("T2 ==> "+ [Link]());
[Link]();

[Link] ("T1 ==> "+ [Link]());


[Link] ("T2 ==> "+ [Link]());
}
}

Output :
T1 ==> NEW
T2 ==> NEW
T1 ==> RUNNABLE
T2 ==> NEW
T1 ==> RUNNABLE
T2 ==> RUNNABLE
Thread is running !!
Thread is running !!

Thread Creation and simple programs:


Step 1:
 In Java, an object of the Thread class can represent a thread.
 Thread can be implemented through any one of two ways:
1. Extending the [Link] Class
2. Implementing the [Link] Interface

Khan S. Alam 3 [Link]


Unit-6 Multi-threading

Extending the [Link] Class


Syntax:
class MyThread extends Thread
{
}

Implementing the [Link] Interface


Syntax:
MyThread implements Runnable
{
}

Step 2:
 After declaration of thread class, we have to override run( ) method in class.

Step 3:
 Now we can create object of thread if needed.

In short we have to follow following these steps:


1. Extend the [Link] Class.
2. Override the run( ) method in the subclass from the Thread class to define the code
executed by the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor
by subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for
running.

Khan S. Alam 4 [Link]


Unit-6 Multi-threading

The following program demonstrates a single thread creation extending the "Thread"
Class:

class MyThread extends Thread


{
String s=null;

MyThread (String s1)


{
s=s1;
start();
}

public void run()


{
[Link](s);
}
}

public class RunThread


{
public static void main(String args [])
{
MyThread m1 = new MyThread ("Thread started....");
}
}

Output of the Program is:


C:\>javac [Link]
C:\>java RunThread
Thread started....

Khan S. Alam 5 [Link]


Unit-6 Multi-threading

Q.5 What is multithreading environment?


Multithreading in Java:
 Java provides built-in support for multithreaded programming.
 Multithreading in java is a process of executing multiple threads simultaneously.
 In a thread-based multitasking environment, the thread is the smallest unit of
dispatchable code. This means that a single program can perform two or more tasks
simultaneously.
 For instance, a text editor can format text at the same time that it is printing, as long
as these two actions are being performed by two separate threads.
 Multithreading enables you to write very efficient programs that make maximum use
of the CPU, because idle time can be kept to a minimum.
 Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
 But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading:


1) Reduces the computation time.
2) Improves performance of an application.
3) Threads distribute the same address space so it saves the memory.
4) Context switching between threads is usually less costly than between processes.
5) Cost of communication between threads is comparatively low.
6) You can perform many operations together so it saves time.
7) Threads are independent so it doesn't affect other threads if exception occur in a
single thread.
8) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.

Multithreading in Java can be achieved by two ways:


1. By inheriting the Thread class OR
2. By implementing the Runnable interface

Inheriting the Thread Class:


 Here you have to inherit the Thread class properties into your custom class by
extending the Thread class.
 After extending this Thread class, you have to override the run() method of the
Thread class.
 After the object is created, start() function needs to be called in order to start the
execution of the thread.

Khan S. Alam 6 [Link]


Unit-6 Multi-threading

Program code:

class MultithreadingDemo extends Thread


{
public void run()
{
[Link] ("My thread is in running state.");
}

public static void main(String args[])


{
MultithreadingDemo obj = new MultithreadingDemo();
[Link]();
}
}

Implementing the Runnable Interface


 The easiest way to create a thread is to create a class that implements the Runnable
interface.
 Runnable abstracts a unit of executable code. You can construct a thread on any
object that implements Runnable. To implement Runnable, a class need only
implement a single method called run( ), which is declared like this: public void run( )
 Inside run( ), you will define the code that constitutes the new thread. This thread
will end when run( ) returns.
 After you create a class that implements Runnable, you will instantiate an object of
that class and call the start() function to start the thread's run() function

Program Code:

class MultithreadingDemo implements Runnable


{
public void run()
{
[Link]("My thread is in running state.");
}

public static void main (String args [])


{
MultithreadingDemo obj = new MultithreadingDemo();
Thread tobj =new Thread(obj);
[Link]();
}
}

Khan S. Alam 7 [Link]


Unit-6 Multi-threading

Q.6 What is synchronization? What is use of synchronization in Java? Explain with


example.
Q.7 Explain thread synchronization in detail.
Synchronization:
 When two or more threads need access to a shared resource, they need some way
to ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization.
 Any method is specified with the keyword synchronized is only executed by one
thread at a time. If any thread wants to implement the synchronized method, firstly
it has to obtain the objects lock. If the lock is already held by another thread, then
calling thread has to wait.
 Key to synchronization is the concept of the monitor (also called a semaphore). A
monitor is an object that is used as a mutually exclusive lock, or mutex.
 Only one thread can own a monitor at a given time. When a thread acquires a lock, it
is said to have entered the monitor. All other threads attempting to enter the locked
monitor will be suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor.
 A thread that owns a monitor can reenter the same monitor if it so desires.
 Synchronized methods are useful in those situations where methods are executed
concurrently, so that these can be intercommunicate control the state of an object in
ways that can corrupt the state if.
 Stack implementations usually define the two operations push and pop of elements
as synchronized, that’s why pushing and popping are mutually exclusive process.
 For Example:
If several threads were sharing a stack, if one thread is popping the element on the
stack then another thread would not be able to pushing the element on the stack.

Use of Synchronization:
 If we not use synchronization, and let two or more threads access a shared resources
at the same time, it will lead to distorted results.
 Consider an example, Suppose we have two different threads T1 and T2 starts
execution and save certain values in a file [Link] which will be used to
calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns,
T2 change the values saved by T1 in the file [Link]. Now obviously T1 will
return wrong result.
 To prevent such problems, synchronization was introduced. With synchronization in
above case, once T1 starts using [Link] file, this file will be locked (LOCK
mode), and no other thread will be able to access or modify it until T1 returns.

You can synchronize your code in either of two ways. Both involve the use of the
synchronized keyword, and both are examined here.
1. Using Synchronized Methods
2. The synchronized Block Statement

Khan S. Alam 8 [Link]


Unit-6 Multi-threading

1. Using Synchronized Methods


 Synchronization is easy in Java, because all objects have their own implicit monitor
associated with them.
 To enter an object’s monitor, just call a method that has been modified with the
synchronized keyword.
 While a thread is inside a synchronized method, all other threads that try to call it (or
any other synchronized method) on the same instance have to wait.
 To exit the monitor and relinquish control of the object to the next waiting thread,
the owner of the monitor simply returns from the synchronized method.

2. The synchronized Block Statement


 While creating synchronized methods within classes that you create is an easy and
effective means of achieving synchronization, it will not work in all cases.
 To understand why, consider the following. Imagine that you want to synchronize
access to objects of a class that was not designed for multithreaded access. That is,
the class does not use synchronized methods.
 Further, this class was not created by you, but by a third party, and you do not have
access to the source code.
 Thus, you can’t add synchronized to the appropriate methods within the class.

This is the general form of the synchronized statement:


synchronized(object)
{
// statements to be synchronized
}

Here, object is a reference to the object being synchronized. A synchronized block ensures
that a call to a method that is a member of object occurs only after the current thread has
successfully entered object’s monitor.

Example of Synchronized method:


public class MyTest
{
static int i = 0;

public static void main(String[] args)


{
new Thread(t1).start();
new Thread(t2).start();
}

private synchronized static void countMe()


{
i++;
[Link] ("Current Counter is: " + i);
}

Khan S. Alam 9 [Link]


Unit-6 Multi-threading

private static Runnable t1 = new Runnable()


{
public void run()
{
try
{
for(int i=0; i<5; i++){
countMe("t1");
}
} catch (Exception e){}
}
};

private static Runnable t2 = new Runnable()


{

public void run()


{
try
{
for(int i=0; i<5; i++){
countMe("t2");
}
} catch (Exception e){}
}
};

Remember the following points related to lock and synchronization:


 Only methods (or blocks) can be synchronized, Classes and variable cannot be
synchronized.
 Each object has just one lock.
 All methods in a class need not to be coordinated. A class can have both
synchronized and non-synchronized methods.
 If a class has both synchronized and non-synchronized methods, multiple threads
can still access the class's non-synchronized methods.
 If a thread goes to sleep, it holds any locks it has—it doesn't let go them.
 A thread can obtain more than one lock.
 You can synchronize a block of code rather than a method.
 Constructors cannot be synchronized

Khan S. Alam 10 [Link]


Unit-6 Multi-threading

Q.8 What is java thread model.


The Java Thread Model:
 The Java run-time system depends on threads for many things and alt the class
libraries are designed with multithreading in mind.
 Threads exist in several states. A thread can be running. It can be ready to run as
soon as it gets CPU time. A running thread can be suspended. which temporarily
suspends its activity.
 A suspended thread can then be resumed, allowing it to pick up where it left off.
 A thread can be blocked when waiting for a resource. At any time, a thread can be
terminated, which halts its execution immediately. Once terminated, a thread
cannot be resumed.

Java thread model can be defined in the following three sections:


1) Thread Priorities:
 Each thread has its own priority in Java. Thread priority is an absolute integer value.
 Thread priority decides only when a thread switches from one running thread to
next, called context switching.
 Priority does increase the running time of the thread or gives faster execution.
 Java assigns to each thread a priority that determines how that thread should be
treated with respect to the others.
 Thread priorities are integers that specify the relative priority of one thread to
another.

2) Synchronization:
 Java supports an asynchronous multithreading, any number of thread can run
simultaneously without disturbing other to access individual resources at different
instant of time or shareable resources.
 But some time it may be possible that shareable resources are used by at least two
threads or more than two threads, one has to write at the same time, or one has to
write and other thread is in the middle of reading it. For such type of situations and
circumstances Java implements synchronization model called monitor.
 For this purpose, Java implements a model of inter process synchronization the
monitor.
 The monitor is a control mechanism. You can think of a monitor as a very small box
that can hold only one thread. Once a thread enters a monitor, all other threads
must wait until that thread exits the monitor.

3) Messaging:
 A program is a collection of more than one thread. Threads can communicate with
each other.
 Java supports messaging between the threads with lost-cost.
 It provides methods to all objects for inter-thread communication.
 As a thread exits from synchronization state, it notifies all the waiting threads.

Khan S. Alam 11 [Link]


Unit-6 Multi-threading

Q.9 What is Priority of a Thread (Thread Priority).


Thread Priority:
 In a Multi threading environment, thread scheduler assigns processor to a thread
based on priority of thread.
 Whenever we create a thread in java, it always has some priority assigned to it.
 Priority can either be given by JVM while creating the thread or it can be given by
programmer.
 Each thread have a priority. Priorities are represented by a number between 1 and
10.
 In most cases, thread schedular schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on
JVM specification that which scheduling it chooses.

3 constants defiend in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the
value of MAX_PRIORITY is 10.

Explanation of Thread Priority:


1. We can modify the thread priority using the setPriority() method.
2. Thread can have integer priority between 1 to 10
3. Java Thread class defines following constants –
4. At a time many thread can be ready for execution but the thread with highest
priority is selected for execution
5. Thread have default priority equal to 5.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread


{

public void run()


{
[Link] ("running thread name is:"+[Link]().getName());
[Link] ("running thread priority is:"+[Link]().getPriority());
}

public static void main (String args [])


{
TestMultiPriority1 m1 = new TestMultiPriority1();
TestMultiPriority1 m2 = new TestMultiPriority1();
[Link] (Thread.MIN_PRIORITY);
[Link] (Thread.MAX_PRIORITY);
[Link]();
[Link]();

Khan S. Alam 12 [Link]


Unit-6 Multi-threading

}
}

Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Q.10 What is ThreadGroup class.


ThreadGroup class:
 The ThreadGroup class manages groups of threads for Java applications.
 A ThreadGroup can contain any number of threads.
 The threads in a group are generally related in some way, such as who created them,
what function they perform, or when they should be started and stopped.
 ThreadGroups can contain not only threads but also other ThreadGroups.
 The top-most thread group in a Java application is the thread group named main.
 You can create threads and thread groups in the main group. You can also create
threads and thread groups in subgroups of main.
The result is a root-like hierarchy of threads and thread groups:

The ThreadGroup class has methods that can be categorized as follows:


Collection Management Methods:
 Methods that manage the collection of threads and subgroups contained in the
thread group.
 Methods That Operate on the Group: These methods set or get attributes of the
ThreadGroup object.
 Methods That Operate on All Threads within a Group: This is a set of methods that
perform some operation, such as start or resume, on all the threads and subgroups
within the ThreadGroup.

Khan S. Alam 13 [Link]


Unit-6 Multi-threading

Access Restriction Methods:


 ThreadGroup and Thread allow the security manager to restrict access to threads
based on group membership.

Constructors of ThreadGroup class


There are only two constructors of ThreadGroup class.
1) ThreadGroup(String name): creates a thread group with given name.
2) ThreadGroup(ThreadGroup parent, String name): creates a thread group with given
parent group and name.

Important methods of ThreadGroup class


 There are many methods in ThreadGroup class. A list of important methods are
given below.
 Let's see a code to group multiple threads.

1. ThreadGroup tg1 = new ThreadGroup("Group A");


2. Thread t1 = new Thread (tg1, new MyRunnable(),"one");
3. Thread t2 = new Thread (tg1, new MyRunnable(),"two");
4. Thread t3 = new Thread (tg1, new MyRunnable(),"three");

 Now all 3 threads belong to one group. Here, tg1 is the thread group name,
MyRunnable is the class that implements Runnable interface and "one", "two" and
"three" are the thread names.
 Now we can interrupt all threads by a single line of code only.
 [Link]().getThreadGroup().interrupt();

Khan S. Alam 14 [Link]


Unit-6 Multi-threading

ThreadGroup Example
File: [Link]

public class ThreadGroupDemo implements Runnable


{

public void run()


{
[Link]([Link]().getName());
}

public static void main(String[] args)


{
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg1, runnable,"one");


[Link]();

Thread t2 = new Thread(tg1, runnable,"two");


[Link]();

Thread t3 = new Thread(tg1, runnable,"three");


[Link]();

[Link] ("Thread Group Name: "+[Link]());


[Link]();
}
}

Output:
one
two
three
Thread Group Name: Parent ThreadGroup
[Link] [name=Parent ThreadGroup,maxpri=10]
Thread [one,5,Parent ThreadGroup]
Thread [two,5,Parent ThreadGroup]
Thread [three,5,Parent ThreadGroup]

Khan S. Alam 15 [Link]


Unit-6 Multi-threading

Q.11 What is Inter-thread communication.


Inter-thread communication:
 Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
 Cooperation (Inter-thread communication) is a mechanism in which a thread is
paused running in its critical section and another thread is allowed to enter (or lock)
in the same critical section to be executed.

It is implemented by following methods of Object class:


1) wait()
2) notify()
3) notifyAll()

1) wait() method
 Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
 The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description:
 public final void wait() throws InterruptedException: waits until object is notified.
 public final void wait(long timeout)throws InterruptedException: waits for the
specified amount of time.

2) notify() method
 Wakes up a single thread that is waiting on this object's monitor.
 If any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()

3) notifyAll() method
 Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

Example of inter thread communication in java:


 Let's see the simple example of inter thread communication.

class Customer
{
int amount = 10000;

synchronized void withdraw(int amount)


{
[Link]("going to withdraw...");

Khan S. Alam 16 [Link]


Unit-6 Multi-threading

if([Link]<amount)
{
[Link]("Less balance; waiting for deposit...");
Try
{
wait();
}
catch(Exception e)
{}
}

[Link]-=amount;
[Link]("withdraw completed...");
}

synchronized void deposit(int amount)


{
[Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}
}

class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){[Link](15000);}
}
.start();
new Thread()
{
public void run(){[Link](10000);}
}
.start();
}}

Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Khan S. Alam 17 [Link]

You might also like