Unit 3 Java
Unit 3 Java
1. Threads
Typically, we can define threads as a sub-process with lightweight with the smallest unit of
processes and also has separate paths of execution. The main advantage of multiple threads is
efficiency (allowing multiple things at the same time. For example, in MS Word, one thread
automatically formats the document while another thread is taking user input. Another
advantage is quick response, if we use multiple threads in a process and if a thread gets stuck
due to lack of resources or an exception, the other threads can continue to execution, allowing
the process (which represents an application) to continue to be responsive.
In a simple way, a Thread is a:
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
There are different states Thread transfers into during its lifetime, let us know about those states
in the following lines: in its lifetime, a thread undergoes the following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State
New State
By default, a Thread will be in a new state, in this state, code has not yet been run and the
execution process is not yet initiated.
Active State
A Thread that is a new state by default gets transferred to Active state when it invokes the start()
method, his Active state contains two sub-states namely:
• Runnable State: In This State, The Thread is ready to run at any given time and it’s the
job of the Thread Scheduler to provide the thread time for the runnable state preserved
threads. A program that has obtained Multithreading shares slices of time intervals which
are shared between threads hence, these threads run for some short span of time and wait in
the runnable state to get their schedules slice of a time interval.
• Running State: When The Thread Receives CPU allocated by Thread Scheduler, it
transfers from the “Runnable” state to the “Running” state. and after the expiry of its given
time slice session, it again moves back to the “Runnable” state and waits for its next time
slice.
Waiting/Blocked State
If a Thread is inactive but on a temporary time, then either it is a waiting or blocked state, for
example, if there are two threads, T1 and T2 where T1 needs to communicate to the camera and
the other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its
work, at this state T1 is parked in waiting for the state, and in another scenario, the user called
two Threads T2 and T3 with the same functionality and both had same time slice given by
Thread Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple
threads parked in a Blocked/Waiting state Thread Scheduler clears Queue by rejecting
unwanted Threads and allocating CPU on a priority basis.
Sometimes the longer duration of waiting for threads causes starvation, if we take an example
like there are two threads T1, T2 waiting for CPU and T1 is undergoing a Critical Coding
operation and if it does not exist the CPU until its operation gets executed then T2 will be
exposed to longer waiting with undetermined certainty, In order to avoid this starvation
situation, we had Timed Waiting for the state to avoid that kind of scenario as in Timed Waiting,
each thread has a time period for which sleep() method is invoked and after the time expires the
Threads starts executing its task.
Terminated State
We can run Threads in Java by using Thread Class, which provides constructors and methods
for creating and performing operations on a Thread, which extends a Thread class that can
implement Runnable Interface. We use the following constructors for creating the Thread:
• Thread
• Thread(Runnable r)
• Thread(String name)
• Thread(Runnable r, String name)
import java.io.*;
import java.util.*;
2. Runnable Interface
import java.io.*;
import java.util.*;
3. Thread Synchronization
Multi-threaded programs may often come to a situation where multiple threads try to access
the same resources and finally produce erroneous and unforeseen results.
Why use Java Synchronization?
Java Synchronization is used to make sure by some synchronization method that only one
thread can access the resource at a given point in time.
Java Synchronized Blocks
Java provides a way of creating threads and synchronizing their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronize on the same object and can only have one thread executed inside them at a time.
All other threads attempting to enter the synchronized block are blocked until the thread inside
the synchronized block exits the block.
This synchronization is implemented in Java with a concept called monitors or locks. 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.
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes.
It ensures that the shared resources are safe and in order.
2. Thread Synchronization in Java
Thread Synchronization is used to coordinate and ordering of the execution of the threads in a
multi-threaded program. There are two types of thread synchronization are mentioned below:
• Mutual Exclusive
• Cooperation (Inter-thread communication in Java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
There are three types of Mutual Exclusive mentioned below:
• Synchronized method.
• Synchronized block.
• Static synchronization.
import java.io.*;
import java.util.*;
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
class Test {
synchronized void test_function(int n)
{
// synchronized method
for (int i = 1; i <= 3; i++) {
System.out.println(n + i);
try {
Thread.sleep(500);
}
catch (Exception e) {
System.out.println(e);
}
}
}
}
// Driver Class
public class GFG {
// Main function
public static void main(String args[])
{
// only one object
final Test obj = new Test();
4. Thread Communication
Inter-thread communication in Java 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. Inter-thread communication is also known as Cooperation in Java.
The process of testing a condition repeatedly till it becomes true is known as polling. Polling is
usually implemented with the help of loops to check whether a particular condition is true or
not. If it is true, a certain action is taken. This wastes many CPU cycles and makes the
implementation inefficient.
For example, in a classic queuing problem where one thread is producing data, and the other is
consuming it.
How Java multi-threading tackles this problem?
To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All these
methods belong to object class as final so that all classes have them. They must be used within
a synchronized block only.
• wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
• notify(): It wakes up one single thread called wait() on the same object. It should be noted
that calling notify() does not give up a lock on a resource.
• notifyAll(): It wakes up all the threads called wait() on the same object.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Example:
class Customer{
int amount=10000;
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...");
}
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();
}}
5. AWT Components
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications. AWT
is heavyweight, which means that its components consume resources from the underlying
operating system (OS). The java.awt package contains AWT API classes such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
Why AWT is Platform Independent?
The Java AWT utilizes the native platform subroutine to create API components such as
TextField, CheckBox, and buttons. This results in a different visual format for these
components on different platforms such as Windows, MAC OS, and Unix. The reason for this
is that each platform has a distinct view of its native components. AWT directly calls this native
subroutine to create the components, resulting in an AWT application resembling a Windows
application on Windows OS, and a Mac application on the MAC OS. In simpler terms, the AWT
application’s appearance adapts to the platform it is running on.
AWT is platform independent even after the AWT components are platform dependent because
of the points mentioned below:
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through Abstract
API which are platform independent. Abstract API allows Java to isolate platform-specific
details, making code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent. Because
of this, it ensures that AWT functionality remains consistent across different environments.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
• Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
• Containers: AWT provides containers like panels, frames, and dialogues to organize and
group components in the Application.
• Layout Managers: Layout Managers are responsible for arranging data in the containers
some of the layout managers are BorderLayout, FlowLayout, etc.
• Event Handling: AWT allows the user to handle the events like mouse clicks, key presses,
etc. using event listeners and adapters.
• Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images
and write text in the components of a Java Application.
5. Component Class
The Component class is the superclass of all components. A component class can be linked with
a page, components of web applications. Component clearly shows that is the graphical
representation of an Object.
1. public void add(Component c): This method inserts a component into a Container by
taking a component as a parameter.
2. public void setSize(int width, int height): This method sets the size of the component by
taking height and width as parameters.
3. public void setLayout(LayoutManager lm): This method sets the layout to set the
components in a particular manner by taking LayoutManager as a parameter.
4. public void setVisible(boolean status): This method sets the visibility of a component to
visible or not. If it sets to true then the component will be visible in the output else if it sets
to false or not defined component won’t be visible in the output.
Types of Components in Component Class
1. Container
2. Button
3. Label
4. Checkbox
5. Choice
6. List
All these components are present in java.awt package. We can import each of the components
individually i.e., import java.awt.Button, import java.awt.Container etc.
Container
The Container is a component that will be used to extend other components such as window,
panel, Frame, Dialog, and Applet as shown in the above diagram.
• Window: The Window is a Container that doesn’t include borders and a menu bar. We
must use another window, frames, and dialogue box to create a Window. Creating an
instance is the way to create a Window Container.
• Panel: The Panel is also a Container that doesn’t include a title bar, menu, or border. It is
a container that holds components like buttons, textfield, etc. Creating an instance is the
way to create a Panel Container and can add components.
• Frame: The Frame is a container used while creating an AWT application. It can have
components like title bar, menu bars, borders and also buttons, scroll bar, etc.
• Dialog: The Dialog box is a container that will display the message that we want to display
on the screen.
Button
A button is a labeled component when clicked performs an event. It is created by the Button
class. When clicked it performs some action by sending an instance of ActionEvent by AWT.
ActionEvent calls processEvent on the button and it receives all the events and performs action
by calling the processActionEvent method of its own. To do such things it needs to implement
ActionListener. The Declaration of Button Class will be
public class Button extends Component implements Accessible
It contains 2 constructors:
1. Button() : This constructor will create a button with no label
2. Button(String label) : This constructor creates a button with label value as a value when
we creates an object
Label
It is used to show text in the Container. It will displays text in the form of READ-ONLY, which
cannot be changed by the user directly. We need to create an instance of Label Class to create
a Label. The Declaration of Label Class will be
public class Label extends Component implements Accessible
It has 3 constructors:
1. Label() : Creates an Empty Label.
2. Label(String labelname) : Creates a Label with labelname as parameter value.
3. Label(String labelname, int align) : Creates a Label with labelname as parameter value
and proper alignments.
It is used to create a Checkbox in the Container. It can get a value either true or false by checking
and unchecking the checkbox.
• checked – returns true
• unchecked – returns false
It can be created by creating an instance of Checkbox. The Declaration of Label Class will be
public class Checkbox extends Component implements ItemSelectable, Accessible
It has 5 constructors:
1. Checkbox() : Creates a checkbox with empty label
2. Checkbox(String checkboxlabel) : Creates a Checkbox with checkboxlabel as parameter
value.
3. Checkbox(String checkboxlabel, boolean status) : Creates a Checkbox with checkboxlabel
as parameter value and sets the status either true or false.
4. Checkbox(String checkboxlabel, boolean status, CheckboxGroup cbgroup) : Creates a
Checkbox with checkboxlabel as parameter value and sets the status to the specified
checkbox group.
5. Checkbox(String checkboxlabel, CheckboxGroup cbgroup, boolean status) : Creates a
Checkbox with checkboxlabel as parameter value for the specified cbgroup and sets the
status.
/ importing AWT class
import java.awt.*;
5. Choice
It is used to show the popup menu to select any item from the menu items. The selected choice
will be shown at the top of the menu bar. We need to create an instance of Choice Class to
create a Choice. The Declaration of Choice Class will be
public class Choice extends Component implements ItemSelectable, Accessible
It has 1 constructor:
Choice() : Creates a new Choice menu of items
import java.awt.*;
public class SelectItems {
// main method
public static void main(String args[])
{
// creating a Frame
Frame frame = new Frame();
The List Object creates a list of items in which we can choose one or multiple items at a time.
We need to create an instance of List Class to create a List. The Declaration of Label Class will
be
public class List extends Component implements ItemSelectable, Accessible
It has 3 constructors:
1. List() : Creates a new Scrolling List
2. List(int noofrows) : Creates a new Scrolling List which displays the list of items with
given no. of rows visible with parameter noofrows.
3. List(int noofrows, boolean multi) : Creates a new Scrolling list which displays the list of
items with given no. of rows visible and allows to select multiple items at a time.
import java.awt.*;
public class SelectList {
// main method
public static void main(String args[])
{
// creating frame1
Frame frame1 = new Frame();
// creating frame2
Frame frame2 = new Frame();
6. Layout Manager
The Layout Managers are used to arrange components in a particular manner. The Java Layout
Managers facilitates us to control the positioning and size of the components in GUI forms.
Layout Manager is an interface that is implemented by all the classes of layout managers. There
are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Example
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Flow Layout
Flow Layout is a simple layout manager that arranges components in a row, left to right, wrapping
to the next line as needed. It is ideal for scenarios where components need to maintain their natural
sizes and maintain a flow-like structure.
import javax. swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Grid Layout
Grid Layout arranges components in a grid with a specified number of rows and columns. Each cell
in the grid can hold a component. This layout manager is ideal for creating a uniform grid of
components, such as a calculator or a game board.
import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
frame.add(new JButton("Button " + i));
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Card Layout
Card Layout allows components to be stacked on top of each other, like a deck of cards. Only one
component is visible at a time, and you can switch between components using methods like next()
and previous(). This layout is useful for creating wizards or multi-step processes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CardLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Example");
CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
JButton button1 = new JButton("Card 1");
JButton button2 = new JButton("Card 2");
JButton button3 = new JButton("Card 3");
cardPanel.add(button1, "Card 1");
cardPanel.add(button2, "Card 2");
cardPanel.add(button3, "Card 3");
frame.add(cardPanel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1.addActionListener(e -> cardLayout.show(cardPanel, "Card 2"));
button2.addActionListener(e -> cardLayout.show(cardPanel, "Card 3"));
button3.addActionListener(e -> cardLayout.show(cardPanel, "Card 1"));
}
}
GroupLayout
GroupLayout is a versatile and complex layout manager that provides precise control over the
positioning and sizing of components. It arranges components in a hierarchical manner using
groups. GroupLayout is commonly used in GUI builders like the one in NetBeans IDE.
import javax.swing.*;
public class GroupLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GroupLayout Example");
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(button1)
.addComponent(button2));
layout.setVerticalGroup(layout.createParallelGroup()
.addComponent(button1)
.addComponent(button2));
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GridBagLayout
GridBagLayout is a powerful layout manager that allows you to create complex layouts by
specifying constraints for each component. It arranges components in a grid, but unlike
GridLayout, it allows components to span multiple rows and columns and have varying sizes.
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayout Example");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(button1, constraints);
constraints.gridx = 1;
panel.add(button2, constraints);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
7. AWT Events
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling,
etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events
Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User Interface
(GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
Delegation Event model
• It has Sources and Listeners.
• Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
• Listeners: Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.
Code-Approaches
The three approaches for performing event handling are by placing the event handling code in
one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
The Event listener represent the interfaces responsible to handle events. Java provides us various
Event listener classes but we will discuss those which are more frequently used. Every method of
an event listener method has a single argument as an object which is subclass of EventObject class.
For example, mouse event listener methods will accept instance of MouseEvent, where
MouseEvent derives from EventObject.
EventListner interface
It is a marker interface which every listener interface has to extend.This class is defined in java.util
package.
Class declaration
Following is the declaration for java.util.EventListener interface:
public interface EventListener
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.
Sr. No. Control & Description
ActionListener
1
This interface is used for receiving the action events.
ComponentListener
2
This interface is used for receiving the component events.
3 ItemListener
This interface is used for receiving the item events.
KeyListener
4
This interface is used for receiving the key events.
MouseListener
5
This interface is used for receiving the mouse events.
TextListener
6
This interface is used for receiving the text events.
WindowListener
7
This interface is used for receiving the window events.
AdjustmentListener
8
This interface is used for receiving the adjusmtent events.
ContainerListener
9
This interface is used for receiving the container events.
MouseMotionListener
10
This interface is used for receiving the mouse motion events.
FocusListener
11
This interface is used for receiving the focus events.
8. Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
Pros of using Adapter classes:
o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.
java.awt.event Adapter classes
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
javax.swing.event Adapter classes
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Example:
import java.awt.*;
import java.awt.event.*;
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}