Unit III Multi Threading Notes
Unit III Multi Threading Notes
1. It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
Each process has an address in memory. In other words, each process allocates a
separate memory area. A process is heavyweight. Cost of communication between the
process is high.
Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
Threads share the same address space. A thread is lightweight. Cost of communication
between the thread is low.
Unit III- Multithreading in JAVA
---------------------------------------------------------------------------------------------------------------------
Q3. Define a Thread
As shown in the above figure, a 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.
Unit III- Multithreading in JAVA
Thread class
Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface
---------------------------------------------------------------------------------------------------------------------
Q4. With a neat sketch explain Life cycle of a Thread (Thread States)
A thread can be in one of the five states. In general terms, a thread can running. It can
be ready to run as soon as it gets the CPU time. A running thread can be suspended,
which is a temporary halt to its execution. It can later be resumed. A thread can be
blocked when waiting for the resource. A thread can be terminated.
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. Blocked/Terminated
5. Destroy
Unit III- Multithreading in JAVA
Newborn State: When we create a thread, it is said to be in the new born state. At
this state we can do the following:
Runnable State: A runnable state means that a thread is ready for execution and
waiting for the availability of the processor. That is the thread has joined the queue of
the threads for execution. If all the threads have equal priority, then they are given
time slots for execution in the round robin fashion, first-come, first-serve manner. The
thread that relinquishes the control will join the queue at the end and again waits for
its turn. This is known as time slicing. Running State:
Unit III- Multithreading in JAVA
Running state: Running state means that the processor has given its time to the
thread for it execution. The thread runs until it relinquishes the control or it is pre-
empted by the other higher priority thread. As shown in the fig. a running thread can
be preempted using the suspend(), or wait(), or sleep() methods.
Blocked state: A thread is said to be in the blocked state when it is prevented from
entering into runnable state and subsequently the running state.
Dead state: Every thread has a life cycle. A running thread ends its life when it has
completed execution. It is a natural death. However we also can kill the thread by
sending the stop () message to it at any time.
-------------------------------------------------------------------------------------------------------------------
Q5. How can a thread be created? Or what are the two ways of creating a thread
Thread class:
Unit III- Multithreading in JAVA
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
1. Thread ()
2. Thread (String name)
Thread (Runnable r)
3. Thread (Runnable r,String name)
public void start (): starts the execution of the thread. JVM calls the run()
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
Unit III- Multithreading in JAVA
Output:thread is running
Thread priorities are used by the thread scheduler to decide when and which thread
should be allowed to run. In theory, higher-priority threads get more CPU time than
lower-priority threads.
In practice, the amount of CPU time that a thread gets often depends on several
factors besides its priority. (For example, how an operating system implements
multitasking can affect the relative availability of CPU time.) A higher-priority thread can
also preempt a lower-priority one. For instance, when a lower-priority thread is running
and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it
will preempt the lower priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
This is its general form:
Here, level specifies the new priority setting for the calling thread. The value of level
must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities are defined as static final
variables within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
{
System. out. println(" Child 1 is started");
}
}
class PThread2 extends Thread
{
public void run()
{
System. out. println(" Child 2 is started");
}
}
class PThread3 extends Thread
{
public void run ()
{
System. out. println(" Child 3 is started");
}
class PTest
Unit III- Multithreading in JAVA
{
public static void main (String args[])
{
pt1.start();
pt2.start();
pt3.start();
-----------------------------------------------------------------------------------------------------------------------
Q7. Thread Synchronization in Java with an example
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.
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.
Unit III- Multithreading in JAVA
class Bank
{
int bal;
public Bank()
{
bal=5000;
}
public void withdraw(int bal1)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
bal=bal-bal1;
System.out.println("Balance is ="+bal);
}
}
Class ConBank implements Runnable
{
Bank b;
public ConBank(Bank b1)
{
b=b1;
}
public void run()
{
b.withdraw(500);
}
}
class MainBank
{
public static void main(String args[])
{
Bank o1= new Bank();
ConBank c1= new ConBank(o1);
Thread t1=new Thread(c1);
Thread t2= new Thread(c1);
t1.start();
t2.start();
}
}
Unit III- Multithreading in JAVA
Output
Balance is:4000
Balance is:4000
where synchronized is the keyword, method contains the type, and method_name
represents the name of the method, and para_list indicate the list of the parameters.
class Bank
{
int bal;
public Bank()
{
bal=5000;
}
public synchronized void withdraw(int bal1)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
bal=bal-bal1;
System.out.println("Balance is ="+bal);
}
Unit III- Multithreading in JAVA
}
Class ConBank implements Runnable
{
Bank b;
public ConBank(Bank b1)
{
b=b1;
}
public void run()
{
b.withdraw(500);
}
}
class MainBank
{
public static void main(String args[])
{
Bank o1= new Bank();
ConBank c1= new ConBank(o1);
Thread t1=new Thread(c1);
Thread t2= new Thread(c1);
t1.start();
t2.start();
}
}
Output
Balance is:4500
Balance is:4000
---------------------------------------------------------------------------------------------------------------------
• wait() tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.
class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try {
wait();
}
catch(InterruptedException e)
{
Unit III- Multithreading in JAVA
{
System.out.println("InterruptedException caught");
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
Q q; Producer (Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while(true
)
Unit III- Multithreading in JAVA
{
q.put(i++);
}
}
} //end of Producer
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}//end of Consumer
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
---------------------------------------------------------------------------------------------------------------------
Unit III- Multithreading in JAVA
Whenever we want stop a thread we can stop from running using "stop()" method of
thread class. It's general form will be as follows: Thread. Stop(); This method
causes a thread to move from running to dead state. A thread will also move to
dead state automatically when it reaches the end of its method.
Blocking Thread: A thread can be temporarily suspended or blocked from entering
into the runnable and running state by using the following methods:
These methods cause the thread to go into the blocked state. The thread will return to
the runnable state when the specified time is elapsed in the case of sleep(), the
resume() method is invoked in the case of suspend(), and the notify() method is
called in the case of wait().