0% found this document useful (0 votes)
12 views54 pages

Java Multithreading Overview

The document covers the concepts of multithreading, I/O, and generic programming in Java, detailing thread creation, synchronization, and communication. It explains the advantages of multithreading, such as improved CPU utilization and responsiveness, and outlines the life cycle of a thread along with its various states. Additionally, it discusses thread priorities, methods of the Thread class, and the creation of threads through implementing the Runnable interface or extending the Thread class.

Uploaded by

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

Java Multithreading Overview

The document covers the concepts of multithreading, I/O, and generic programming in Java, detailing thread creation, synchronization, and communication. It explains the advantages of multithreading, such as improved CPU utilization and responsiveness, and outlines the life cycle of a thread along with its various states. Additionally, it discusses thread priorities, methods of the Thread class, and the creation of threads through implementing the Runnable interface or extending the Thread class.

Uploaded by

Jeyakumar Vjk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

22CS202 JAVA PROGRAMMING

UNIT 3 MULTITHREADING,
I/O AND GENERIC
PROGRAMMING
UNIT I MULTITHREADING, I/O AND GENERIC
PROGRAMMING

Syllabus:
Multithreaded Programming: Creating a Thread, Thread
Priorities, Synchronization, Inter thread Communication – I/O:
I/O Basics, Reading Console Input, Writing Console Output,
Reading and Writing Files – Generics: Introduction, Generic
class, Bounded Types, Generic Methods, Generic Interfaces,
Generic Restrictions.

2
Multithreaded Programming
• One of the Feature of Java
• To improve the performance
• CPU utilization
• Speed up application execution
• Makes our program more responsive

22CS202 Java Programming 3


Multithreaded Programming
Thread:
• Thread -lightweight sub process(same Memory space , communicate,
Less space in memory and Less processor Time)
• Smallest unit of processing
• It is a separate path of execution.
• Independent
• Exception in one thread, will not affect other thread.
• Uses Shared Memory
• It consist of PC, stack and Local variables.
22CS202 Java Programming 4
Multithreaded Programming
Thread:

22CS202 Java Programming 5


Multithreaded Programming
Multithreading:
• executing multiple threads simultaneously – Multithreading
• execution of two or more parts of a program
• Each part of such a program is called a thread,
• maximum utilization of CPU

22CS202 Java Programming 6


Multithreaded Programming
Multithreading- Advantage
• doesn't block the user
• can perform many operations together, so it saves time.
• independent

22CS202 Java Programming 7


Multithreaded Programming
Problem over a single Thread:
For example, when you play online cricket game, you sometimes
see such a situation where the game does not show the updated
score but still displays graphics properly.
Here, displaying graphics of game and updating scores are two
different jobs that are to be handled at the same time.
To overcome these problems, Java supports multithreaded
programming that enables a single program to perform multiple
tasks simultaneously.

22CS202 Java Programming 8


Multithreading
Real time Example

• Consider word processing program that checks the spelling of


words in a document while writing the document. This is
possible only if each action is performed by a separate thread.
• browser that starts rendering a web page while it is still
downloading the rest of page.

22CS202 Java Programming 9


Multithreaded Programming
Multitasking:
• Multitasking is a process of executing multiple tasks
simultaneously.
• multiple processes share common processing resources
such as a CPU.
• Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)

22CS202 Java Programming 10


Multithreaded Programming
Process-based Multitasking (Multiprocessing)
• Each process has an address in memory
• and allocates a separate memory area
• process is heavyweight
• Cost of communication between the process is high
• Switching from one process to another requires
• some time for -loading registers- memory maps- updating lists

22CS202 Java Programming 11


Multithreaded Programming
Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

22CS202 Java Programming 12


Multithreaded Programming
Life Cycle of a Thread

22CS202 Java Programming 13


Multithreaded Programming
• A thread can be in any of the following states:
• New
• Runnable
• Running
• Blocked
• Waiting
• Timed Waiting
• Terminated

22CS202 Java Programming 14


Multithreaded Programming
• New:
• newly created thread
• Execution not started
• starts the thread using start() method
• Runnable:
• the thread is ready for execution
• waiting for the availability of the processor.

22CS202 Java Programming 15


Multithreaded Programming
• Running:
• processor has given its time to the thread for execution.
• thread keeps running until
• suspended using suspend() method
• sleep(time).
• wait () method.
• notify() method.
• A thread is pre-empted by a higher priority thread.

22CS202 Java Programming 16


Multithreaded Programming
• Blocked:
• prevented from entering into runnable state
• Waiting for I/O to complete
• Waiting:
• waiting for another thread to perform a task for a specified interval of time.
• Terminated:
• runnable thread enters the dead or terminated state when it successfully
completes its task
• terminated due to any error or even forcefully killed.

22CS202 Java Programming 17


Multithreaded Programming
Main() Thread:
• if you do not create any thread- there will be one thread- Main()
• Whenever Java program starts, main thread is created automatically.
• Main () -Parent Thread others are Child Thread.
• Main thread is starting and finishing thread & terminates
• To control the execution of the main thread by creating a Thread object
and then using methods of Thread class
• To do so, we will have to create a Thread object by calling
currentThread()
• Thread obj = [Link]();
22CS202 Java Programming 18
Multithreaded Programming

22CS202 Java Programming 19


Multithreaded Programming
Java program to find the thread used by JVM

public class MainThread


{
public static void main(String[] args)
{
// Create a Thread object by calling currentThread() method of class Thread.
Thread obj = [Link]();

[Link]("Current thread is " +obj); // line 8


[Link]("Name of current thread is " +[Link]());
}
} Output:
Current thread is Thread[main,5,main]
22CS202 Java Programming 20
Multithreaded Programming
• Java program in which we will control main thread and also change name of main thread.
public class MainThreadDemo
{
public static void main(String[] args)
{
// Create a Thread object by calling currentThread() method of class Thread.
Thread obj = [Link]();
[Link]("Current thread is " +obj);
[Link]("Name of current thread is " +[Link]());

[Link]("New Thread"); // Changing name of main thread.


[Link]("Name of current thread after changing name is " +obj);
[Link]("Main thread existing");
}
} Output:
Current thread is Thread[main,5,main]
Name of current thread is main
Name of current thread after changing name22CS202is Thread[New
Java Programming Thread,5,main] 21
Multithreaded Programming
• In Java, Thread class contains several constructors for creating threads
for tasks and methods for controlling threads.
• It is a predefined class declared in [Link] default package.
Thread Class Constructor
• Thread(): This is a basic and default constructor without parameters. It
simply creates an object of Thread class.
• Thread(String name): It creates a new thread object with specified
name to a thread.

22CS202 Java Programming 22


Multithreaded Programming
• Thread(Runnable r): It creates a thread object by passing a
parameter r as a reference to an object of the class that
implements Runnable interface.
• Thread(Runnable r, String name): This constructor creates a
thread object by passing two arguments r and name. Here,
variable r is a reference of an object of class that implements
Runnable interface.

22CS202 Java Programming 23


Multithreaded Programming
Methods of Thread Class:
 currentThread(): The currentThread() returns the reference of
currently executing thread.
 public static Thread currentThread()

 sleep(): The sleep() method puts currently executing thread to sleep


for specified number of millisecondsgetPriority(): Obtain a thread’s
priority.
 public static void sleep(long milliseconds) throws InterruptedException
 public static void sleep(long milliseconds, int nanoseconds ) throw
InterruptedException

22CS202 Java Programming 24


Multithreaded Programming
Methods of Thread Class:
yield(): The yield() method pauses the execution of current
thread and allows another thread of equal or higher priority that
are waiting to execute.
public static void yield()

activeCount(): This method returns the number of active


threads.
public static int activeCount()
22CS202 Java Programming 25
Multithreaded Programming
Methods of Thread Class:
start(): The start() method is used to start the execution of a
thread by calling its run() method
public void start()
run(): The run() method moves the thread into running state.
public void run()
getName(): This method returns the name of the thread.
public final String getName()

22CS202 Java Programming 26


Multithreaded Programming
Methods of Thread Class:
setName(): This method is used to set the name of a thread.
public final void setName(String name)
getPriority(): This method returns the priority of a thread. he
maximum priority is 10, the minimum priority is 1, and normal
priority is 5.
public final int getPriority() // Return type is an integer.
setPriority(): This method is used to set the priority of a thread.
public final void setPriority(int newPriority)
22CS202 Java Programming 27
Multithreaded Programming
Methods of Thread Class:
isAlive(): This method is used to check the thread is alive or
not.
public final native boolean isAlive()
join(): The join() method is used to make a thread wait for
another thread to terminate its process.
public final void join() throw InterruptedException
stop(): This method is used to stop the thread.
public final void stop()
22CS202 Java Programming 28
Multithreaded Programming
Methods of Thread Class:
suspend(): The suspend() method is used to suspend or pause
a thread.
public final void suspend()
resume(): This method is used to resume the suspended
thread
public final void resume()
isDaemon(): This method is used to check the thread is daemon
thread or not.
public final boolean isDaemon()
22CS202 Java Programming 29
Multithreaded Programming
Thread Priorities:
• Thread priorities are integers no assigned to thread
• Thread Scheduler to decide which thread should be allowed to
execute.
• Thread priorities are represented by a number from 1 to 10
• thread with the highest priority is selected by the scheduler to be
executed first.
• The default priority of a thread is 5

22CS202 Java Programming 30


Multithreaded Programming
Thread Priorities:
• MIN_PRIORITY = 1
• NORM_PRIORITY = 5
• MAX_PRIORTY = 10
• Thread scheduler selects the thread for execution on the first-come,
first-serve basis
• When multiple threads are ready for execution, the highest priority
thread is selected and executed by JVM
• getPriority() is used to determine the priority of a thread

22CS202 Java Programming 31


Multithreaded Programming- Thread
Priorities
public class A implements Runnable
{ [Link]("Priority of Thread: "
public void run() +[Link]());
{ [Link]("Name of Thread: "
+[Link]());
[Link]([Link]()); //
This method is static. [Link]();
} }
public static void main(String[] args) } Output:
{ Priority of Thread: 5
A a = new A(); Name of Thread: NewThread
Thread t = new Thread(a, "NewThread"); Thread[NewThread,5,main]

22CS202 Java Programming 32


Multithreaded Programming
Thread Priorities:
• Get and Set Thread Priority:
• [Link]() method returns priority of given thread.
• [Link]() method changes the priority of thread to the value
newPriority.
• Beyond minimum(1) and maximum(10) limit.

22CS202 Java Programming 33


Multithreaded Programming-Thread Priorities

public class A implements Runnable Thread t = new Thread(a, "NewThread");


{ [Link](2); // Setting the priority of
public void run() thread.
{
[Link]("Priority of Thread: "
[Link]([Link]()) +[Link]());
; // This method is static. [Link]("Name of Thread: "
} +[Link]());
public static void main(String[] args) [Link]();
{ }
A a = new A(); }
22CS202 Java Programming 34
Multithreaded Programming- Creation of Thread
Every Java program has at least one thread called main thread.
When a program starts, main thread starts running immediately.

Apart from this main thread, we can also create our own threads
in a program that is called child thread.

Every child threads create from its main thread known as parent
thread.

• Creation of Thread
• [Link] implementing Runnable Interface
• [Link] extending Thread Class
22CS202 Java Programming 35
Multithreaded Programming- Creation of
Thread

22CS202 Java Programming 36


Multithreaded Programming- Creation of
Thread
• Extending Thread Class in Java
1. Create a class that extends the Thread class. In order to
extend a thread, we will use a keyword extends.
Class Myclass extends Thread

2. Now in this newly created class, define a method run(). The


run() method contains the actual task that thread will perform.
public void run()
{
// statements to be executed.
} 22CS202 Java Programming 37
Multithreaded Programming- Creation of
Thread
• Extending Thread Class in Java
3. Create an object of newly created class so that run() method is
available for execution.
Myclass obj = new Myclass();
4. Now create an object of Thread class and pass the object reference
variable created to the constructor of Thread class.
Thread t = new Thread(obj);
or,
Thread t = new Thread(obj, "threadname");
5. Run the thread. For this, we need to call to start() method of Thread
class because we cannot call run() method directly.
[Link](); 22CS202 Java Programming 38
Multithreaded Programming
2. By extending Thread Class
create a new class that extends Thread, and then to create
an instance of that class.
class Myclass implements Runnable

22CS202 Java Programming 39


Multithreaded Programming
public class MyThread implements Runnable [Link]("Main thread running");
{
public void run() // Create an object of MyThread class.
{ MyThread th = new MyThread();
[Link]("New thread running ");
for(int i = 1; i <= 5; i++) // Create an object of Thread class and pass
{ reference variable th to Thread class constructor.
[Link](i);
Thread t = new Thread(th);
}
[Link]([Link]());
[Link](); // This thread will execute statements
} inside run() method of MyThread object.
public static void main(String[] args) }
{ }
22CS202 Java Programming 40
Multithreaded Programming-
Synchronizing Threads
• Consider two passengers are trying to book seats from Chennai to
Neyveli in cholan Express in railway reservation system.
• Both passengers are trying to book tickets from different locations
and only two seats are available.
• Since the available number of seats is only two but booked seats
are three. This problem happened due to asynchronous access to
the railway reservation system.
• In this realtime scenario, both passengers can be considered as
threads, and the reservation system can be considered as a single
object, which is modified by these two threads asynchronously.

22CS202 Java Programming 41


Multithreaded Programming-
Synchronizing Threads

22CS202 Java Programming 42


Multithreaded Programming-
Synchronizing Threads
• This asynchronous problem is known as race condition in
which multiple threads access the same object and modify the
state of object inconsistently.
• The solution to this problem can be solved by a synchronization
mechanism.
• Using lock synchronization can be carried out.
• The process of acquiring and releasing object lock (monitor) of
an object is handled by Java runtime system (JVM).

22CS202 Java Programming 43


Multithreaded Programming
• Synchronizing Threads:
General Syntax:

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

Synchronization is mainly used to


• To prevent thread interference.
• To prevent consistency problem..
22CS202 Java Programming 44
Multithreaded Programming
• Types of Synchronization:
• Process Synchronization: The simultaneous execution of multiple
threads or processes to reach a state such that they commit to a certain
sequence of actions.
• Thread Synchronization: When more than one thread tries to access a
shared resource, it should be ensured that the resource will be used by
only one thread at a time.

22CS202 Java Programming 45


Multithreaded Programming
• Thread Synchronization:
two types of thread synchronization
 Mutual Exclusive
 Synchronized method.
 Synchronized block.
 Static synchronization.
 Cooperation (Inter-thread communication in java)

22CS202 Java Programming 46


Multithreaded Programming
 Mutual Exclusive
 helps keeping threads from interfering with one another while sharing
data. This can be done by three ways in java:
 by synchronized method
 by synchronized block
 by static synchronization

22CS202 Java Programming 47


Multithreaded Programming
 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.
• E.G
• public synchronized void print(String str)
{ // declaration
}

22CS202 Java Programming 48


Multithreaded Programming
 Synchronized Block:
• Synchronized block can be used to perform synchronization on any specific
• resource of the method.
• For ex. If you have 20 lines of code in a method, and you want to synchronize
• only 5 lines, synchronized block can be
• E.G
• synchronized (object reference expression)
{ // Code Block
}

22CS202 Java Programming 49


Multithreaded Programming
 Static Synchronized :
 If you make any static method as synchronized, the lock will be on the class not
on object.
 Use synchronized keyword on the static method to perform static
synchronization.
 E.G:
 synchronized static void print(int n)
{ // declaration part
}

22CS202 Java Programming 50


Multithreaded Programming
 Inter-Thread Communication:
 defined as the process of allowing synchronized threads to communicate with
each other.
 reducing CPU idle time
 Inter-Thread Communication can be implemented by following methods
of Object class
 wait()
 notify()
 notifyAll()

22CS202 Java Programming 51


Multithreaded Programming
 Inter-Thread Communication:
 wait() Method
 causes current thread to release the lock
 Wait until either another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.
 Syntax:
 public final void wait()throws InterruptedException
 public final void wait(long timeout)throws InterruptedException

22CS202 Java Programming 52


Multithreaded Programming
 Inter-Thread Communication:
 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.
 Syntax: public final void notify()
 Syntax: public void notifyAll()

22CS202 Java Programming 53


Multithreaded Programming
Use of Thread in Java:
• server-side programs - to handle multiple clients on network or
internet
• creating games and animations
• Generally, threads can be used to perform more than one task
simultaneously.

22CS202 Java Programming 54

You might also like