Module IV Multithreading, Event Handling
Module IV Multithreading, Event Handling
Module IV
MULTITHREADING , EVENT HANDLING
Syllabus
Multithreading in java :
Multithreading in Java is a process of executing multiple threads simultaneously.
Module IV Page 1
CGB1201-JAVA PROGRAMMING
● Threads consume CPU in the best possible manner, hence enables multi
processing. Multi threading reduces idle time of CPU which improves performance
of application.
package demotest;
The java contains a built-in interface Runnable inside the [Link] package.
The Runnable interface implemented by the Thread class that contains all the methods that
are related to the threads.
To create a thread using Runnable interface, follow the step given below.
Output
Module IV Page 3
CGB1201-JAVA PROGRAMMING
Thread class provide constructors and methods to create and perform operations on
a [Link] class extends Object class and implements Runnable interface.
● Thread( )
To create a thread using Thread class, follow the step given below.
● Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
● Step-2: Override the run( ) method with the code that is to be executed by the
thread. The run( ) method must be public while overriding.
● Step-3: Create the object of the newly created class in the main( ) method.
● Step-4: Call the start( ) method on the object created in the above step.
Module IV Page 4
CGB1201-JAVA PROGRAMMING
}
}
Output
Thread class also defines many methods for managing threads. Some of them are,
Method Description
Module IV Page 5
CGB1201-JAVA PROGRAMMING
The Thread class in java also contains methods like stop( ), destroy( ), suspend( ), and
resume( ). But they are deprecated.
Module IV Page 6
CGB1201-JAVA PROGRAMMING
{
[Link](1000); // Pause the thread execution for 1000
milliseconds.
}
catch(InterruptedException e) {
[Link]([Link]());
}
}
}
public static void main(String[] args)
{
MyThread t1 = new MyThread("Cut the ticket");
MyThread t2 = new MyThread("Show your seat number");
[Link]();
[Link]();
}
}
Output:
Module IV Page 7
CGB1201-JAVA PROGRAMMING
Explanation:
1. In the preceding example program, we have created two threads on two objects of
MyThread class. Here, we created two objects to represent two tasks. When we will run the
above program, the main thread starts running immediately. Two threads will generate
from the main thread that will perform two different tasks.
2. When [Link](); is executed by JVM, it starts execution of code inside run() method and
print the statement “Cut the ticket” on the console.
3. When JVM executes [Link](1000); inside the try block, it pauses the thread
execution for 1000 milliseconds. Here. sleep() method is a static method that is used to
pauses the execution of thread for a specified amount of time.
For example, [Link](1000); will pause the execution of thread for 1000 milliseconds
(1 sec). 1000 milliseconds means 1 second. Since sleep() method can throw an exception
named InterruptedException, we will catch it into catch block.
4. Meanwhile, JVM executes [Link](); and second thread starts execution of code inside the
run() method almost simultaneously. It will print the statement “Show your seat number”.
Now, the second thread will undergo to sleep for 1000 milliseconds.
5. When the pause time period of the first thread is elapsed, it will reenter into running
state and starts the execution of code inside run() method. The same process will also
happen for second thread. In this manner, both threads will perform two tasks almost
simultaneously.
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Terminated
Module IV Page 8
CGB1201-JAVA PROGRAMMING
New state
When a thread instance/object is created, thread will be created and moved to “new” state.
Thread obj = new Thread(new MyRunnable()); //thread will be created and moved to
“new” state.
Runnable state
When start() method is called, thread moves to runnable state. A separate method
call stack will be created with run method being at the bottom of the call stack.
[Link]([Link]());
Module IV Page 9
CGB1201-JAVA PROGRAMMING
A thread can also return to the “runnable state” after coming back from a running,
sleeping, waiting or blocked state.
Running state
● In running state, thread will be running, in fact code present inside run() method
will be executing.
● A thread can move out of the “running state” to runnable, non-runnable or dead
state for various reasons.
● Also we can move running thread to other state explicitly by calling yield(), sleep(),
wait(), join or stop() method etc.
Non runnable state (Sleeping state, Waiting state and Blocked state)
● A non-runnable thread is a paused thread because of certain reasons like
unavailability of resources, waiting for another thread to finish, user explicitly
paused etc...
● When this non runnable thread is ready for re-run it will move to runnable state, but
not to running state.
1. Sleeping state: A thread moves into the “sleeping state “when sleep() is called on a
running thread.
2. Waiting state: A thread moves into the “waiting state” when wait() is called on a
running Thread
3. Blocked state: A thread moves into the “blocked state” when join() is called or
Module IV Page 10
CGB1201-JAVA PROGRAMMING
Dead state
● When run method execution is completes, thread moves to dead state.
● We can also call stop() or destroy() method explicitly to move a running thread
into “dead state” but the methods have been deprecated.
Program:
try {
// Thread is in waiting state (sleep)
[Link]("Thread is going to sleep...");
[Link](1000);
} catch (InterruptedException e) {
[Link]("Thread is interrupted.");
}
[Link]("Thread is terminated.");
}
// Runnable state
[Link]();
[Link]("Thread is now RUNNABLE.");
}
}
Module IV Page 11
CGB1201-JAVA PROGRAMMING
Output:
Differences
Module IV Page 12
CGB1201-JAVA PROGRAMMING
Thread Priority
In java, the thread priority range from 1 to 10. Priority 1 is considered as the
lowest priority, and priority 10 is considered as the highest priority. The thread with
more priority allocates the processor first.
he java programming language Thread class provides two methods setPriority(int), and
getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and
they are listed below.
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes
an integer range from 1 to 10 as an argument and returns nothing (void).
Example
[Link](4);
or
[Link](MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It
does not take any argument and returns the name of the thread as String.
Module IV Page 13
CGB1201-JAVA PROGRAMMING
Example
Program
[Link]("first");
[Link]("second");
[Link](4);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Output:
Module IV Page 14
CGB1201-JAVA PROGRAMMING
Inside SampleThread
Current Thread: second
Inside SampleThread
Current Thread: first
Thread Synchronization
The synchronization is the process of allowing only one thread to access a
shared resource at a time.
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the same
monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
class Customer {
[Link]("Going to withdraw...");
try {
} catch (InterruptedException e) {
[Link]();
[Link]("Going to deposit...");
[Link] += amount;
Module IV Page 16
CGB1201-JAVA PROGRAMMING
class Test {
// Withdraw thread
});
// Deposit thread
});
Output:
Case study:
a) Write a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is
even, the second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of the cube of the number.
Program:
import [Link].*;
class NumberGenerator extends Thread {
public void run() {
Random random = new Random();
while (true) {
int num = [Link](100);
[Link]("Generated Number: " + num);
if (num % 2 == 0) {
[Link]("Square of " + num + " is: " + (num * num));
} else {
[Link]("Cube of " + num + " is: " + (num * num * num));
}
try {
[Link](1000);
} catch (InterruptedException e) {
[Link](e);
}
}
Module IV Page 18
CGB1201-JAVA PROGRAMMING
}
}
public class MultiThreadedApp {
public static void main(String[] args) {
new NumberGenerator().start();
}
}
Output:
Generated Number: 12
Square of 12 is: 144
Generated Number: 7
Cube of 7 is: 343
Generated Number: 4
Square of 4 is: 16
Generated Number: 15
Cube of 15 is: 3375
Generated Number: 8
Square of 8 is: 64
Generated Number: 9
Cube of 9 is: 729
Explanation:
Module IV Page 19
CGB1201-JAVA PROGRAMMING
Output Explanation:
● Generated Number: 12 → It's even, so the program prints Square of 12 is: 144.
● Generated Number: 7 → It's odd, so the program prints Cube of 7 is: 343.
This pattern continues, printing the square for even numbers and the cube for odd
numbers.
Java AWT
Java AWT (Abstract Window Toolkit) is a GUI (Graphical User Interface) toolkit for
Java applications, allowing developers to create windowed applications. It's part of Java's
standard library and provides components like buttons, text fields, and labels to create user
interfaces.
Module IV Page 20
CGB1201-JAVA PROGRAMMING
Button
In Java AWT, the Button class is a fundamental GUI component used to create a
clickable button. It is commonly used to trigger actions or events when clicked by the user.
Here’s an in-depth look at its features, methods, and an example of usage:
● Package: [Link]
● Superclass: [Link]
● Constructor: Button() or Button(String label)
● Purpose: The Button class is used for creating interactive buttons in Java AWT
applications. It enables users to perform an action by clicking on the button, which
can then trigger an event.
Module IV Page 21
CGB1201-JAVA PROGRAMMING
Program
import [Link].*;
import [Link].*;
public class ButtonExample extends Frame {
// Label to show output in the window
Label label;
public ButtonExample() {
// Setup frame
setTitle("Button Example");
setSize(300, 200);
setLayout(new FlowLayout());
// Create and add button with ActionListener
Button button = new Button("Click Me");
[Link](e -> [Link]("Button
clicked!"));
Module IV Page 22
CGB1201-JAVA PROGRAMMING
}
}
Output:
Label
In Java AWT, the Label class is used to display a single line of non-editable text.
Labels are typically used to show messages, instructions, or to identify other components in
a GUI (like text fields or buttons).
Module IV Page 23
CGB1201-JAVA PROGRAMMING
Program
import [Link].*;
Module IV Page 24
CGB1201-JAVA PROGRAMMING
// Create labels
Label label1 = new Label("Label with default alignment");
Label label2 = new Label("Centered Label", [Link]);
Label label3 = new Label("Right-aligned Label", [Link]);
setVisible(true);
}
1. Label Creation:
○ Label label1 = new Label("Label with default
alignment"); creates a left-aligned label (default alignment).
○ Label label2 = new Label("Centered Label",
[Link]); creates a label with centered text.
Module IV Page 25
CGB1201-JAVA PROGRAMMING
Checkbox
In Java AWT, the Checkbox class is used to create a checkable box that represents a
binary choice, meaning it can be either selected (checked) or unselected (unchecked).
Checkboxes are often used to gather multiple-choice selections from users.
Module IV Page 26
CGB1201-JAVA PROGRAMMING
Program
import [Link].*;
import [Link].*;
public class SimpleCheckboxExample extends Frame {
public SimpleCheckboxExample() {
// Setup frame
setTitle("Checkbox Example");
setSize(250, 100);
setLayout(new FlowLayout());
// Create checkbox
Checkbox checkbox = new Checkbox("Subscribe");
Label statusLabel = new Label("Checkbox state: Off");
Module IV Page 27
CGB1201-JAVA PROGRAMMING
}
public static void main(String[] args) {
new SimpleCheckboxExample();
}
}
Output
Explanation
Window Setup: The window (Frame) is titled "Checkbox Example" and has a size of
250x100 pixels, with components arranged in a flow (left to right).
Components:
Choice
In Java AWT, the Choice class is used to create a dropdown list (also called a combo
box) that allows the user to choose one item from a list of options. The Choice component
is useful when you want to limit the user to selecting only one item from a predefined set of
choices.
Module IV Page 28
CGB1201-JAVA PROGRAMMING
Method Description
Program
package m4;
import [Link].*;
import [Link].*;
public class SimpleChoiceExample extends Frame {
private Label colorLabel;
public SimpleChoiceExample() {
setTitle("Choice Example");
setSize(250, 150);
setLayout(new FlowLayout());
// Create a Choice component
Choice colorChoice = new Choice();
Module IV Page 29
CGB1201-JAVA PROGRAMMING
[Link]("Red");
[Link]("Green");
[Link]("Blue");
// Create a Label to display the selected color
colorLabel = new Label("Selected Color: None");
// Add ItemListener to handle selection and update label
[Link](e ->
[Link]("Selected Color: " + [Link]())
);
// Add components to the frame
add(colorChoice);
add(colorLabel);
setVisible(true);
}
public static void main(String[] args) {
new SimpleChoiceExample();
}
}
Explanation
Module IV Page 30
CGB1201-JAVA PROGRAMMING
List
In Java AWT, the List class is used to create a list of items that users can select
from. Unlike a Choice component, which displays a single item at a time in a dropdown
format, a List can show multiple items at once and allows for single or multiple selections,
depending on its configuration.
Program
import [Link].*;
import [Link].*;
public class SimpleListExample1 extends Frame {
Module IV Page 31
CGB1201-JAVA PROGRAMMING
Output :
Module IV Page 32
CGB1201-JAVA PROGRAMMING
Explanation
Case Study :
b) Develop a simple calculator application using Java AWT components such as Text
Field, Button, and Label. Implement event handlers to perform arithmetic operations
(addition, subtraction, multiplication, division) when the user clicks on the buttons.
Program
import [Link].*;
import [Link].*;
Module IV Page 33
CGB1201-JAVA PROGRAMMING
Module IV Page 34
CGB1201-JAVA PROGRAMMING
Output:
Module IV Page 35
CGB1201-JAVA PROGRAMMING
Program
import [Link].*;
import [Link].*;
public class SimpleGUIExample {
public static void main(String[] args) {
// Create a frame (Window)
Frame f = new Frame("Simple GUI Example");
// Create components with abbreviated names
Label l = new Label("Select your choice:");
Checkbox cb = new Checkbox("Accept Terms");
Choice c = new Choice();
List li = new List();
Button b = new Button("Submit");
// Add items to the Choice and List
[Link]("Option 1");
[Link]("Option 2");
[Link]("Option 3");
[Link]("Apple");
[Link]("Mango");
[Link]("Banana");
// Set the layout for the frame
[Link](new FlowLayout());
// Add components to the frame
[Link](l);
[Link](cb);
Module IV Page 36
CGB1201-JAVA PROGRAMMING
[Link](c);
[Link](li);
[Link](b);
// Button click event handling
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedChoice = [Link]();
String selectedListItem = [Link]();
boolean isChecked = [Link]();
Output :
Module IV Page 37
CGB1201-JAVA PROGRAMMING
Event handling :
Event handling in Java is a mechanism that allows programs to respond to user
interactions, such as button clicks, mouse movements, and key presses. Java's
event-handling system is part of the AWT (Abstract Window Toolkit) and Swing libraries
and follows a delegation event model. In this model, events are dispatched to designated
objects (known as listeners) that are responsible for handling specific events.
1. Event Sources: These are the objects that generate events. Examples include GUI
components like buttons, text fields, checkboxes, etc. Each source can trigger
multiple types of events (e.g., mouse events, action events).
2. Events: Events are objects that represent specific user interactions. Java provides a
variety of event classes (e.g., ActionEvent, MouseEvent, KeyEvent) to
represent different interactions.
3. Event Listeners: Event listeners are interfaces that define the methods required to
handle specific types of events. Listeners must implement these methods and be
registered with an event source to receive events.
4. Event Handlers: The actual methods that perform the actions when an event
occurs. These methods are defined in the listener interfaces and are called
automatically when an event occur
1. Identify the Event Source: Determine which component will generate the event,
such as a button.
2. Implement the Listener Interface: Create a class that implements the listener
interface(s) relevant to the type of event. For example, ActionListener for
Module IV Page 38
CGB1201-JAVA PROGRAMMING
1. MouseEvent
Method Description
Program
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventExample extends JFrame {
public MouseEventExample() {
setTitle("Mouse Event Example");
setSize(300, 200);
Module IV Page 39
CGB1201-JAVA PROGRAMMING
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// JLabel to show event details
JLabel label = new JLabel("Mouse hasn't interacted yet.");
// MouseListener to detect mouse events
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at: " + [Link]());
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed at: " + [Link]());
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released at: " + [Link]());
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse entered the window!");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse exited the window.");
}
});
// Add label to the frame
add(label);
setVisible(true);
}
public static void main(String[] args) {
new MouseEventExample();
}
}
Output:
Module IV Page 40
CGB1201-JAVA PROGRAMMING
2. KeyEvent
Method Description
Returns the integer code for the key that was
int getKeyCode()
pressed.
Returns the character generated by the key
char getKeyChar()
pressed.
Returns true if the Shift key was pressed
boolean isShiftDown()
when the event occurred.
Returns true if the Control key was pressed
boolean isControlDown()
when the event occurred.
Returns true if the Alt key was pressed when
boolean isAltDown()
the event occurred.
Program
import [Link].*;
import [Link].*;
Module IV Page 41
CGB1201-JAVA PROGRAMMING
setVisible(true);
}
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
Output
Console
Key Pressed: h
Key Pressed: g
Module IV Page 42
CGB1201-JAVA PROGRAMMING
Java Swing
Java Swing is a part of the Java Foundation Classes (JFC) used for creating graphical
user interfaces (GUIs) in Java applications. It provides a rich set of components and a highly
customizable framework that supports a wide range of graphical elements, from basic
components like buttons and labels to more complex components like tables and trees.
JComponent
Module IV Page 43
CGB1201-JAVA PROGRAMMING
JComponent is a key class in the Swing library in Java, providing the foundation for
creating graphical components in a GUI application. It’s the superclass for all Swing
components, including JButton, JLabel, JPanel, and others. JComponent inherits from
Container, meaning it can hold other components and is part of the component hierarchy in
a Java Swing application.
[Link]
Constructors
Constructor Description
JButton() Creates a button with no text or icon.
JButton(String text) Creates a button with specified text.
JButton(Icon icon) Creates a button with an icon but no text.
JButton(String text, Icon icon) Creates a button with both text and an icon.
Module IV Page 44
CGB1201-JAVA PROGRAMMING
Methods
Method Description
void setText(String text) Sets the text displayed on the button.
Returns the text currently displayed on the
String getText()
button.
void setIcon(Icon icon) Sets an icon for the button.
Icon getIcon() Returns the icon used by the button.
void Adds an ActionListener to handle button click
addActionListener(ActionListener l) events.
[Link]
JLabel is a simple yet essential component in Java Swing used to display a short
string or an image. Unlike interactive components like JButton, JLabel is primarily for
displaying information and is non-interactive, meaning users can't click or type into it.
JLabel is found in the [Link] package and is a fundamental part of most GUI
applications, often used for labeling other components or showing static information.
Constructor
Constructor Description
JLabel() Creates an empty label.
JLabel(String text) Creates a label with the specified text.
JLabel(Icon icon) Creates a label with the specified icon.
JLabel(String text, Icon icon, int Creates a label with text, an icon, and
alignment) specified alignment.
Methods
Method Description
void setText(String text) Sets the text displayed by the label.
Module IV Page 45
CGB1201-JAVA PROGRAMMING
[Link]
JList is a component in Java Swing that provides a way to display a list of items
from which users can select one or multiple entries. It’s a versatile and commonly used
component in Swing for presenting options or items in a scrollable, selectable format.
JList is part of the [Link] package and is ideal for cases where users need to
choose from a predefined list of options.
Constructors
Constructor Description
JList() Creates an empty list.
JList(E[] listData) Creates a list from an array of items.
Creates a list using a specified data model,
JList(ListModel<E> dataModel) providing more control.
Methods
Method Description
void setListData(E[] listData) Sets the items in the list from an array.
Module IV Page 46
CGB1201-JAVA PROGRAMMING
JComboBox
Constructors
Constructor Description
JComboBox() Creates an empty combo box.
Creates a combo box containing the elements
JComboBox(E[] items) in the specified array.
Creates a combo box containing the elements
JComboBox(Vector<E> items) in the specified vector.
Methods
Method Description
void addItem(E item) Adds an item to the combo box.
E getSelectedItem() Returns the currently selected item.
void setSelectedItem(Object item) Sets the selected item.
void removeItem(Object item) Removes an item from the combo box.
Sets whether the combo box is editable
void setEditable(boolean editable) (allowing users to type into it).
void Registers an action listener to be notified
addActionListener(ActionListener l) when an item is selected.
Module IV Page 47
CGB1201-JAVA PROGRAMMING
Program
import [Link].*;
import [Link].*;
// JLabel
JLabel l = new JLabel("Choose an option:");
// JComboBox renamed to cb
JComboBox<String> cb = new JComboBox<>(items);
// JButton
JButton b = new JButton("Submit");
setVisible(true);
}
Output
Module IV Page 48
CGB1201-JAVA PROGRAMMING
Important Questions
1. Illustrate with a neat diagram and discuss the life cycle of thread and its priority.
2. Develop a java program for creating four threads to perform the following
operations.
i) Getting N numbers as input
ii) Printing the even numbers
iii) Printing the odd numbers
iv) Computing the average
Module IV Page 49
CGB1201-JAVA PROGRAMMING
3. Show how multi threads are created in java with example program and state the
significance of sleep(), run() and join() methods.
4. Develop a java program that illustrates the uses of wait(), notify(), notifyAll()
methods.
5. Discuss in detail about inter thread communication in java.
6. Develop a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is
even, the second thread computes the square of the number and prints. If the value
is odd, the third thread will print the value of the cube of the number.
7. Classify the swing components in Java and explain any three of them with example
program.
8. Analyse on how events are handled in java. Discuss in detail about it.
9. Classify Java AWT components and explain any three of them with example program.
10. Develop a java program that illustrates event handing such as MouseEvent and
KeyEvent.
11. Develop a calculator application using Java AWT components such as Text Field,
Button, and Label. Implement event handlers to perform arithmetic operations
(addition, subtraction, multiplication, division) when the user clicks on the buttons.
12. Develop a calculator application using Java Swing components such as Text Field,
Button, and Label. Implement event handlers to perform arithmetic operations
(addition, subtraction, multiplication, division) when the user clicks on the buttons.
Module IV Page 50