Unit 2 - Java Programming
Unit 2 - Java Programming
Multithreaded Programming
Concept of Multitasking
Multitasking : Where users of a computer system can
perform multiple actions simultaneously on the machine.
On a single-core CPU,
multithreading only provides the
illusion of parallelism due to
context switching, whereas
parallel programming requires a
multi-core processor to achieve
true parallel execution.
What is a Thread ?
● A Thread is a light-weight process within a process.
● It is the smallest part of the process.
● Threads use shared memory but act independently.
● Therefore, if an exception occurs in one thread, other threads
are not affected despite sharing same memory.
● This allows programs to operate more efficiently by running
multiple tasks simultaneously.
● Threads can be used to perform complicated tasks in the
background without interrupting the main program.
In a simple way, a Thread is a:
● Feature through which we can perform multiple activities within a
single process.
● Lightweight process.
● Series of executed statements.
● Nested sequence of method calls.
Benefits of multithreading
● It maximizes CPU utilization : Multithreading is a Java
feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
○ Multi-processor system : multiple threads execute
simultaneously on different cores.
■ Eg- If there are two threads and two cores , then each
thread would run on individual core.
○ Single-processor system : multiple threads execute on the
single core, one after the other giving an illusion of parallel
processing.
● It saves time by allowing multiple operations to be
performed simultaneously by making fast switches between
threads.
● It doesn't block the user in Client-Server Model : This means
the next client doesn't have to wait until the first client has
States of the Thread
Syntax :
…………….
It can be created by extending the Thread class and overriding its run() method:
After this run() is invoked → this puts the thread in runnable state
Java Thread Class
● Thread is a line of execution within a program.
● Each program can have multiple associated threads.
● Each thread has a priority which is used by the thread scheduler to
determine which thread must run first.
● Java provides a thread class that has various method calls to
manage the behavior of threads by providing constructors
and methods to perform operations on threads.
● A Thread is a program that starts with a method frequently used in
this class only known as the start() method.
● This method looks out for the run() method which is also a method of
this class and begins executing the body of the run() method.
How to Create Threads in Java? → 2. Using Runnable Interface
Runnable Interface
}
Multithreading in Java - By Extending the Thread class
NOTE :
Thread.currentThread() is a static method of the Thread class that returns a reference to the currently executing thread.
The getId() method in Java is used to retrieve the unique identifier (ID) of a thread.
Output :
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Multithreading in Java - By Implementing the Runnable Interface
Output :
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
https://www.programiz.com/online-compiler/68tV1VfM9Db6j
Thread Class vs Runnable Interface
{
synchronized (this)
{ The consume function has a loop to get
while (list.size() == capacity) items from the list. The function checks if
the list is empty, if it is empty then the
wait(); thread gives up the lock and transfers the
System.out.println("Producer produced: control to the producer thread to produce
"+ value); the item and add it to
list.add(value++); the list. If the list is not empty, we remove
notify(); the item from the list. We have the notify
Thread.sleep(1000); method to notify the producer to produce
} the item.
}
}
Infinite Loop: The method runs indefinitely, producing values continuously.
Synchronization (synchronized (this)): Ensures that only one thread can
execute this block at a time.
Wait Condition: (while (list.size() == capacity)
wait() :
● If the shared resource reaches its capacity, the producer thread waits.
● wait(); releases the lock on this, allowing consumer threads to
consume items.
Notify Consumer (notify()); : Wakes up one waiting consumer thread, so it
can consume an item.
Thread Sleep (Thread.sleep(1000); :Introduces a delay before producing
the next item.
sleep() Method :
● Introduces a pause in the execution of the thread.
● Example : Thread.sleep(1000) - delay of 1000 milliseconds
(1 second).
● Why is this required ?
○ Prevents CPU Overload - if not introduced all the threads run
continuously in a tight loop, consuming CPU resources
unnecessarily.
○ Simulates Real-World Processing Time - In real-world scenarios,
producing and consuming data usually takes some time (e.g.,
fetching data from a database, writing to a file, or network delays).
It is used to mimic the delay.
○ Reduces Context Switching Overhead - Continuous context
switching is expensive. A short sleep period allows the CPU to
Is Sleep() mandatory ?
https://www.scaler.com/topics/producer-consumer-problem-in-java/
Readers-Writers Problem
https://onecompiler.com/java/3xbkf3pxe
Summary :
Thread class (Inbuilt class) : The Thread class in Java is part of the
java.lang package and is used to create and manage threads in a
multithreading environment.
Methods of Thread Class
Methods Action Performed
start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of
this thread
run() If this thread was constructed using a separate Runnable run object, then that Runnable
object’s run method is called; otherwise, this method does nothing and returns
sleep(long millis Causes the currently executing thread to sleep (temporarily cease execution) for the
) specified number of milliseconds
Event Handling
What is Event Handling ?
EventObject(Object src)
● Here, src is the object that generates this event.
● EventObject defines two methods:
○ getSource( ) method : returns the source of the event. Its general
form is shown here: Object getSource( )
○ toString( ) : returns the string equivalent of the event.
2. AdjustmentListener
3. ComponentListener
4. ContainerListener
5. FocusListener
7. KeyListener
● keyTyped(KeyEvent e) → Detects when a key is typed.
● keyPressed(KeyEvent e) → Detects when a key is pressed.
● keyReleased(KeyEvent e) → Detects when a key is released.
8. MouseListener
● mousePressed(MouseEvent e) → Detects when a mouse button is pressed.
● mouseClicked(MouseEvent e) → Detects when a mouse button is clicked.
● mouseEntered(MouseEvent e) → Detects when the mouse enters a component.
● mouseExited(MouseEvent e) → Detects when the mouse exits a component.
● mouseReleased(MouseEvent e) → Detects when a mouse button is released.
9. MouseMotionListener
● mouseMoved(MouseEvent e) → Detects when the mouse moves.
● mouseDragged(MouseEvent e) → Detects when the mouse is dragged.
10. MouseWheelListener
● mouseWheelMoved(MouseWheelEvent e) → Detects mouse wheel movement.
11. TextListener
● textChanged(TextEvent e) → Detects changes in text components like text fields and text
areas.
12. WindowListener
● windowActivated(WindowEvent e) → Detects when a window is activated.
● windowDeactivated(WindowEvent e) → Detects when a window is deactivated.
● windowOpened(WindowEvent e) → Detects when a window is opened.
● windowClosed(WindowEvent e) → Detects when a window is closed.
● windowClosing(WindowEvent e) → Detects when a window is about to close.
● windowIconified(WindowEvent e) → Detects when a window is minimized.
● windowDeiconified(WindowEvent e) → Detects when a window is restored from a
minimized state
Example : in the text file
Revision - Interface in JAVA