Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views16 pages

CSE307 Unit3 Multithreading Notes-Modified

The document provides an overview of multithreading in Java, explaining its advantages, the concept of threads, and the lifecycle of a thread. It details how to create threads, manage their priorities, and implement synchronization to control access to shared resources. Additionally, it discusses inter-thread communication methods such as wait, notify, and notifyAll, along with examples of thread creation and synchronization techniques.
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)
7 views16 pages

CSE307 Unit3 Multithreading Notes-Modified

The document provides an overview of multithreading in Java, explaining its advantages, the concept of threads, and the lifecycle of a thread. It details how to create threads, manage their priorities, and implement synchronization to control access to shared resources. Additionally, it discusses inter-thread communication methods such as wait, notify, and notifyAll, along with examples of thread creation and synchronization techniques.
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/ 16

Java Programming

Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared 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) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.
Java Programming
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

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.

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.

Thread Methods

S.N. Modifier Method Description


and Type

1 void start() It is used to start the execution of the thread.

2 void run() It is used to do an action for a thread.

3 static void sleep() It sleeps a thread for the specified amount of


time.
Java Programming

4 static currentThread() It returns a reference to the currently


Thread executing thread object.

5 void join() It waits for a thread to die.

6 int getPriority() It returns the priority of the thread.

7 void setPriority() It changes the priority of the thread.

8 String getName() It returns the name of the thread.

9 void setName() It changes the name of the thread.

10 long getId() It returns the id of the thread.

11 boolean isAlive() It tests if the thread is alive.

12 void suspend() It is used to suspend the thread.

13 void resume() It is used to resume the suspended thread.

14 void stop() It is used to stop the thread.

15 void interrupt() It interrupts the thread.

16 boolean isinterrupted() It tests whether the thread has been


interrupted.

17 static interrupted() It tests whether the current thread has been


boolean interrupted.

18 String toString() It is used to return a string representation of


this thread, including the thread's name,
priority, and thread group.

19 void notify() It is used to give the notification for only one


thread which is waiting for a particular object.

20 void notifyAll() It is used to give the notification to all waiting


threads of a particular object.

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.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
Java Programming

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.


Java Programming

Creating thread
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

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().

public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Thread Example by extending Thread class


class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1 = new Multi();
t1.start();
}
}

Output: thread is running...

Thread Example by implementing Runnable interface


class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
Java Programming
public static void main(String args[])
{
Multi m1 = new Multi();
Thread t1 = new Thread(m1);
t1.start();
}
}

Output:thread is running...

If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your class
that implements Runnable so that your class run() method may execute.

Sleep method
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException


o public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example:
class TestSleepMethod extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TestSleepMethod t1 = new TestSleepMethod();
TestSleepMethod t2 = new TestSleepMethod();
t1.start();
t2.start();
}
}

Output: 11223344
Java Programming

Priority of a Thread (Thread Priority):


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 defined 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.

Example of priority of a Thread:


class TestMultiPriority extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority m1 = new TestMultiPriority ();
TestMultiPriority m2 = new TestMultiPriority ();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

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

Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.

Synchronization is better option where we want to allow only one thread to access the shared
resource.

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

class Table
{
synchronized void printTable(int n) //synchronized method
{
for(int i=1; i<=5; i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java Programming
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t = t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t = t;
}
public void run()
{
t.printTable(100);
}
}

public class TestSynchronization2


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}

Output: 5
10
15
20
25
100
200
300
400
500

Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
Java Programming
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block


o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression)
{
//code block
}

Example:
class Table
{
void printTable(int n)
{
synchronized(this) //synchronized block
{
for(int i=1; i<=5; i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}//end of the method
}

Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Java Programming

Problem without static synchronization


Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of
synchronized method and synchronized block there cannot be interference between t1 and t2 or t3
and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be
interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another
lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this
problem.

Example of static synchronization


In this example we are applying synchronized keyword on the static method to perform static
synchronization.
class Table
{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
}
}
}
}
class MyThread1 extends Thread
{
public void run()
{
Table.printTable(1);
}
}
class MyThread2 extends Thread
{
public void run()
{
Table.printTable(10);
}
}
class MyThread3 extends Thread
{
public void run()
{
Table.printTable(100);
}
}
class MyThread4 extends Thread
{
public void run()
Java Programming
{
Table.printTable(1000);
}
}
public class TestSynchronization4
{
public static void main(String t[])
{
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
MyThread4 t4 = new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

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:

o wait()
o notify()
o 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 waits for the specified amount
InterruptedException of time.
Java Programming
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()

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep


wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or after the specified amount of time, sleep is


notifyAll() methods completed.

Example of inter thread communication in java


class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{
}
}
this.amount -= amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
Java Programming
this.amount += amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test
{
public static void main(String args[])
{
final Customer c = new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}

Output: going to withdraw...


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

Interrupting a Thread
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt()
method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If
the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal
behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Let's first see the
methods provided by the Thread class for thread interruption.

The 3 methods provided by the Thread class for interrupting a thread

o public void interrupt()

o public static boolean interrupted()

o public boolean isInterrupted()

Example of interrupting a thread that stops working


Java Programming
In this example, after interrupting the thread, we are propagating it, so it will stop working. If we
don't want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let's
first see the example where we are propagating the exception.
class TestInterruptingThread extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("task");
}
catch(InterruptedException e)
{
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[])
{
TestInterruptingThread t1=new TestInterruptingThread ();
t1.start();
try
{
t1.interrupt();
}
catch(Exception e)
{
System.out.println("Exception handled "+e);
}
}
}
Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)

Example of interrupting a thread that doesn't stop working

In this example, after interrupting the thread, we handle the exception, so it will break out the sleeping but will
not stop working.

class TestInterruptingThread extends Thread


{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("task");
}
catch(InterruptedException e)
{
System.out.println("Exception handled "+e);
}
System.out.println("thread is running...");
}
Java Programming
public static void main(String args[])
{
TestInterruptingThread t1=new TestInterruptingThread();
t1.start();
t1.interrupt();
}
}

Output: Exception handled


java.lang.InterruptedException: sleep interrupted
thread is running...

isInterrupted and interrupted method

The isInterrupted() method returns the interrupted flag either true or false. The static interrupted()
method returns the interrupted flag afterthat it sets the flag to false if it is true.
public class TestInterruptingThread extends Thread
{
public void run()
{
for(int i=1; i<=2; i++)
{
if(Thread.interrupted())
{
System.out.println("code for interrupted thread");
}
else
{
System.out.println("code for normal thread");
}
}//end of for loop
}
public static void main(String args[])
{
TestInterruptingThread t1 = new TestInterruptingThread();
TestInterruptingThread t2 = new TestInterruptingThread();
t1.start();
t1.interrupt();
t2.start();
}
}
Output:
Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread

You might also like