unit 3-2
unit 3-2
Multi-threading means multiple flow of control. Multi-threading programming is a conceptual paradigm for programming where one
can divide a program into two or more processes which can be run in parallel. There are two main advantages of multi-threading :
Fist, program with multiple threads will, in general, result in better utilization of system resources, including the CPU, because
another line of execution can grab the CPU when one line of execution is blocked. Second, there are several problems better solved
by multiple threads. For example, we can easily write a multi-threaded program to show animation, play music, display documents,
and down load files from the network at the same time.
Java is a multi-threaded language. Java allows to write a program where more than one processes can be executed concurrently
within the single program. Java's threads are often referred to as light weight threads, which means that they run in the same
memory space. Because Java threads run in the same memory space, they can easily communicate among themselves because
an object in one thread can call a method in another thread without any overhead from the operating system. In this Tutorial we will
learn how to do multi-threaded programming in Java.
Basics of a thread
As with the Java concepts, everything about thread are defined in a class Thread. The Thread class encapsulates all of the control
one will need over threads. The Thread class is our only link to manage how threads behave. In this Section, we will learn about :
how to create and run a thread, the life cycle of a thread, and the thread controlling methods.
Illustration 6.1 // Creating and running threads using sub classing Thread //
/* Creating three threads using the class Thread and then running them concurrently. */
class ThreadA extends Thread{
public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("From Thread A with i = "+ -1*i);
}
System.out.println("Exiting from Thread A ...");
}
}
OUTPUT:
From Thread A with i = -1
From Thread A with i = -2
From Thread A with i = -3
From Thread B with j= 2
From Thread A with i = -4
From Thread A with i = -5
Exiting from Thread A ...
... Multithreading is over
From Thread C with k = 1
From Thread B with j= 4
From Thread B with j= 6
From Thread B with j= 8
From Thread B with j= 10
Exiting from Thread B ...
From Thread C with k = 3
From Thread C with k = 5
From Thread C with k = 7
From Thread C with k = 9
Exiting from Thread C ...
In the above simple example, three threads (all of them are of some type) will be executed concurrently. Note that a thread can be
directed to start its body by start() method.
Using the Runnable interface : A second way to create threads is to make use of the Runnable interface. With this approach, first
we have to implement the Runnable interface.[Runnable interface is already defined in the system package java.lang with a single
method run() as below :
When we will create a new thread, actually a new object will be instantiated from this Runnable interface as the target of our thread,
meaning that the thread will look for the code for the run( ) method within our object's class instead of inside the Thread's class. This
is illustrated with an example where two processes Brother and Sister will be executed simultaneously.
OUTPUT:
Thread 21 is running
Thread 22 is running
Thread 23 is running
Thread 25 is running
Thread 26 is running
Thread 27 is running
Thread 24 is running
Thread 28 is running
Status of a Thread
It is some time essential to know some information about threads. There are number of methods defined in Thread which can be
called for getting information about threads. Some of the most commonly used methods for thread's status are listed here :
currentThread( ) : The CurrentThread() is a static method returns the Thread object which is the currently running thread.
setName( String s) : The SetName() method is to assign a name s for a thread prior its execution. This, therefore, identifies the
thread with a string name. This is helpful for debugging multi-threaded programs.
getName( ) : This method returns the current string value of the thread's name as set by SetName().
setPriority (int p) : This method sets the thread's priotity to an integer value p passed in. There are several predefined priotiry
constants defined in class Thread : MIN-PRIORITY, NORM-PRIORTY and MAX-PRIORITY, which are 1, 5, and 10 respectively.
getPriority ( ) : This method returns the thread's current priority, a value between 1 and 10.
isAlive ( ) : This method returns true if the thread is started but not dead yet.
isDaemon ( ) : This method returns true if the thread is a daemon thread.
Synchronization
To solve the critical section problem, one usual concept is known what is called monitor. A monitor is an object which is used as a
mutually exclusive lock ( called mutex). Only one thread may 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 owner thread exits
the monitor. But in Java, there is no such monitor. In fact, all Java object have their own implicit monitor associated with them. Here,
the key word synchronized is used by which method (s) or block of statements can be made protected from the simultaneous
access. With this, when a class is designed with threads in mind, the class designer decides which methods should not be allowed
to execute concurrently. when a class with synchronized method is instantiated, the new object is given its own implicit monitor. The
entire time that a thread is inside of a synchronized method, all other threads that try to call any other synchronized method on the
same instance have to wait. In order to exit the monitor and relinquish control of the object to the next waiting thread the monitor
owner simply needs to return from the method.
Let us illustrate this mechanism with a simple example.
Suppose, we want to maintain a bank account of customers. Several transactions, such as deposite some amount to an account
and withdraw some amount from an account etc. are possible. Now, for a given account, if two or more transactions come
simultaneously then only one transaction should be allowed at a time instead of simulataneous transaction processing so that data
inconsistency will never occur. So, what we need is to synchronize the transaction. Illustration 6.9 is to implement such a task.
Illustration 6.9
/* The following Java application shows how the transactions in a bank can be carried out concurrently. */
class Account {
public int balance;
public int accountNo;
void displayBalance() {
System.out.println("Account No:" + accountNo + "Balance: " + balance);
}
class Demonstration_119{
public static void main(String args[]) {
Account ABC = new Account();
ABC.balance = 1000;
ABC.accountNo = 111;
TransactionDeposit t1;
TransactionWithdraw t2;
t1 = new TransactionDeposit(ABC, 500);
t2 = new TransactionWithdraw(ABC,900);
}
}
OUTPUT:
500 is deposited
Account No:111Balance: 1500
900 is withdrawn
Account No:111Balance: 600
In the above example, the keyword synchronized is used for the methods void deposite(..) and void withdraw(�) so that these
two methods will never run for the same object instance simultaneously.
Alternatively, if one wants to design a class that was not designed for multi-thread access and thus has non-synchronized methods,
then it can be wrapped the call to the methods in a synchronized block. Here is the general form of the synchronized statement :
Inter-thread Communication
There are three ways for threads to communicate with each other. The first is through commonly shared data. All the threads in the
same program share the same memory space. If an object is accessible to various threads then these threads share access to that
object's data member and thus communicate each other.
The second way for threads to communicate is by using thread control methods. There are such three methods by which threads
communicate for each other :
suspend ( ): A thread can suspend itself and wait till other thread resume it.
resume ( ): A thread can wake up other waiting thread (which is waiting using suspend() ) through its resume() method and then
can run concurrently.
join ( ) :This method can be used for the caller thread to wait for the completion of called thread.
The third way for threads to communicate is the use of three methods; wait(), notify(), and notifyAll(); these are defined in class
Object of package java.lang. Actually these three methods provide an elegant inter-process communication mechanism to take
care the deadlock situation in Java. As there is multi-threading in program, deadlock may occur when a thread holding the key to
monitor is suspended or waiting for another thread's completion. If the other thread is waiting for needs to get into the same monitor,
both threads will be waiting for ever. The uses of these three methods are briefed as below :
wait ( ):This method tells the calling thread to give up the monitor and make the calling thread wait until either a time out occurs or
another thread call the same thread's notify() or notifyAll() method.
Notify ( ): This method wakes up the only one (first) waiting thread called wait() on the same object.
notifyAll( ): This method will wake up all the threads that have been called wait( ) on the same object.
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.
In this AWT tutorial, you will learn the basics of the AWT, including how to create windows, buttons,
labels, and text fields. We will also learn how to add event listeners to components so that they can
respond to user input.
By the end of this tutorial, you will have a good understanding of the AWT and be able to create
simple GUIs in Java.
Java AWT Basics
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface (GUI) or
Windows-based Java programs and Java AWT components are platform-dependent, which means
they are shown in accordance with the operating system’s view. 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.
Points about Java AWT components
i. Components of AWT are heavy and platform dependent
ii. AWT has less control as the result can differ because of components are platform dependent.
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.
Understanding how to use BeanFactory is vital for optimizing your application’s performance. To
delve deeper into Java programming, the Java Backend course offers a comprehensive look at
various Java concepts and their applications.
AWT is platform independent even after the AWT components are platform dependent because of
the points mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
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
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.
Note: Container can be added inside another container as it is type of component.
Types of Containers in Java AWT
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or dialog box. The
Window class extends the Container class, which means it can contain other components, such
as buttons, labels, and text fields.
1. Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
1. Frame: The Frame is the container that contains the title bar and border and can have menu
bars.
1. Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Java AWT Tutorial for Beginner & Experienced
Learn the basics of the Abstract Window Toolkit (AWT) in Java, for both beginners and experienced
developers.
Java AWT Label
Java AWT Button
Java AWT TextField
Java AWT Checkbox
Java AWT CheckboxGroup
Java AWT Choice
Java AWT List
Java AWT Canvas
AWT Scrollbar
Java AWT MenuItem & Menu
Java AWT PopupMenu
Java AWT Panel
Java AWT Toolkit
1. Java AWT Label
Syntax of AWT Label
public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an event when clicked on. Button
Class is used for creating a labeled button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible
Java AWT Button Class Constructors
There are two types of Button class constructors as mentioned below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here” button with show click
here as the value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns (col).
4. Java AWT Checkbox
Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelectable, Accessible
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
5. Java AWT CheckboxGroup
CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializable
Note: CheckboxGroup enables the use of radio buttons in AWT.
6. Java AWT Choice
The object of the Choice class is used to show a popup menu of choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectable, Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.
7. Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
8. Java AWT Canvas
Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible
Canvas Class Constructors
1. Canvas():
Creates new Canvas.
2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.
9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible
Java AWT Scrollbar Class Constructors
There are three constructor classes in Java mentioned below:
1. Scrollbar():
It Creates a new vertical Scrollbar in the Application.
2. Scrollbar(int orientation):
Creates a new vertical Scrollbar with the given orientation.
3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the default value and [mini,
maxi] as the lower and higher limit.
10. Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows you to
create individual items that can be added to menus. And Menu is a component used to create a
dropdown menu that can contain a list of MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT PopupMenu is a component that is used for dynamically popping up a menu that appears
when the user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible
12. Java AWT Panel
Java AWT Panel is a container class used to hold and organize graphical components in a Java
Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible
13. Java AWT Toolkit
Java AWT Toolkit class provides us with a platform-independent way to access various system
resources and functionalities. Subclasses of Toolkit are used to bind various components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object
Event Handling Components – Java AWT
Here are some of the event handling components in Java:
Java ActionListener
Java MouseListener
Java MouseMotionListener
Java ItemListener
Java KeyListener
Java WindowListener
Close AWT Window
1. Java ActionListener
Java ActionListner is a interface which responds to the actions performed by the components like
buttons, menu items ,etc.
Syntax of Java ActionListener:
public class ActionListenerExample Implements ActionListener
There is only methods associated with ActionListner class that is actionPerformed().
Syntax of actionPerformed() method:
public abstract void actionPerformed(ActionEvent e);
2. Java MouseListener
Java MouseListner is a interface that responds to the actions performed by mouse events generated
by the user. Example: mouse clicks , mouse movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a component in an Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a component’s bounds.
3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when mouse is moved or dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a component in Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.
4. Java ItemListener
Java ItemListner is an interface which handles events related to item selection and deselection those
that occur with checkboxes, radio buttons, etc. There is only one Method associated with ItemListner
that is itemStateChanged(). This method provides information about the event, i.e. source of the
event and the changed state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)
5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you change the state of key or can be said
for key related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events related to window actions. Events like
opening , closing, minimizing, etc are handled using WindowListener.
Syntax of WindowListener
public interface WindowListener extends EventListener
There are seven methods associated with WindowListener as mentioned below:
1. windowActivated (WindowEvent e):
Responds when window is first opened
2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window
3. windowClosing (WindowEvent e):
Responds after a window has been closed
4. windowDeactivated (WindowEvent e):
Responds when a window is minimized
5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state
6. windowIconified (WindowEvent e):
Responds when a window is activated
7. windowOpened (WindowEvent e):
Responds when a window loses focus
7. Java Adapter classes
Java adapter classes provide the default implementation of listener interfaces.
8. Close AWT Window
At the end we will need to Close AWT Window, So to perform this task we will use dispose() method.
This method releases the resources associated with the window and also removes it from the
screen.
Java AWT Examples
Here are some Java AWT examples:
Hello World in Java AWT
Java AWT Program to create Button
1. Hello World in Java AWT
Hello, World is was the first step in learning Java. So, let us program our first Program in Java AWT
as Hello World using Labels and Frames.
Below is the implementation of the above method:
// Java AWT Program for Hello World
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
// Driver Class
public class AWT_Example {
// main function
public static void main(String[] args)
{
// Declaring a Frame and Label
Frame frame = new Frame("Basic Program");
Label label = new Label("Hello World!");
// Driver Class
public class Button_Example {
// main function
public static void main(String[] args)
{
// Creating instance of frame with the label
Frame frame = new Frame("Example 2");
The Layout managers enable us to control the way in which visual components are arranged in the GUI
forms by determining the size and position of components within the containers.
Types of LayoutManager
There are 6 layout managers in Java
FlowLayout: It arranges the components in a container like the words on a page. It fills the top line from left to right and
top to bottom. The components are arranged in the order as they are added i.e. first components appears at top left, if the
container is not wide enough to display all the components, it is wrapped around the line. Vertical and horizontal gap
between components can be controlled. The components can be left, center or right aligned.
BorderLayout: It arranges all the components along the edges or the middle of the container i.e. top, bottom, right and
left edges of the area. The components added to the top or bottom gets its preferred height, but its width will be the width of
the container and also the components added to the left or right gets its preferred width, but its height will be the remaining
height of the container. The components added to the center gets neither its preferred height or width. It covers the
remaining area of the container.
GridLayout: It arranges all the components in a grid of equally sized cells, adding them from the left to right and top to
bottom. Only one component can be placed in a cell and each region of the grid will have the same size. When the
container is resized, all cells are automatically resized. The order of placing the components in a cell is determined as they
were added.
GridBagLayout: It is a powerful layout which arranges all the components in a grid of cells and maintains the aspect ration
of the object whenever the container is resized. In this layout, cells may be different in size. It assigns a consistent horizontal
and vertical gap among components. It allows us to specify a default alignment for components within the columns or rows.
BoxLayout: It arranges multiple components in either vertically or horizontally, but not both. The components are
arranged from left to right or top to bottom. If the components are aligned horizontally, the height of all components will
be the same and equal to the largest sized components. If the components are aligned vertically, the width of all
components will be the same and equal to the largest width components.
CardLayout: It arranges two or more components having the same size. The components are arranged in a deck, where
all the cards of the same size and the only top card are visible at any time. The first component added in the container will
be kept at the top of the deck. The default gap at the left, right, top and bottom edges are zero and the card components are
displayed either horizontally or vertically.
The Swing package (javax.swing) is a part of Java’s GUI toolkit that provides lightweight,
platform-independent components for building graphical user interfaces. Swing is built on top
of AWT (Abstract Window Toolkit) and provides more flexible and powerful UI components.
1. Importing the Swing Package
To use Swing components, import the following:
java
CopyEdit
import javax.swing.*;
// Create Components
JLabel label = new JLabel("Enter Name:");
JTextField textField = new JTextField();
JButton button = new JButton("Submit");
Explanation:
frame.add(label);
frame.add(button);
frame.setVisible(true);
}
}
Explanation:
6. Swing Containers
Swing provides containers for grouping components.
// Create Panel
JPanel panel = new JPanel();
panel.add(new JLabel("Enter Age:"));
panel.add(new JTextField(10));
panel.add(new JButton("Submit"));
Explanation: