APP - Unit 3
APP - Unit 3
Practice
Unit-3
Advanced Java Programming Paradigms
APP Faculties
Department of Computational Intelligence
SRM Institute of Science and Technology
Objects shared by multiple tasks have to be safe for concurrent access. Such objects are called protected. Tasks accessing such an
object, interact with each other indirectly through the object.
An access to the protected object can be:
• Lock-free, when the task accessing the object is not blocked for a considerable time;
• Blocking, otherwise.
Blocking objects can be used for task synchronization. To the examples of such objects belong:
• Events;
• Mutexes and semaphores;
• Waitable timers;
• Queues
• A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature that allows your
computer to run two or more programs concurrently.
• For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text
editor.
• In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
• Each process has an address in memory. In other words, each process allocates a separate memory area.
• A process is heavyweight.
• Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists,
etc.
• For instance, a text editor can format text at the same time that it is printing, as long as these two actions are
being performed by two separate threads.
• Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the
details.
• A thread is lightweight.
• A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking.
• All the programs have at least one thread, known as the main thread, that is provided by the JVM or Java
Virtual Machine at the starting of the program’s execution.
• Multiple threads of execution can be run concurrently by an application running on the Java Virtual Machine.
The priority of each thread varies.
• Thread is critical in the program because it enables multiple operations to take place within a single method.
The start() method is used to call the void run() method. When start() is called, a new stack is given to the thread, and
run() is invoked to introduce a new thread in the program.
• The Life Cycle of a Thread in Java refers to the state transformations of a thread that begins with
its birth and ends with its death.
• When a thread instance is generated and executed by calling the start() method of the Thread
class, the thread enters the runnable state. When the sleep() or wait() methods of the Thread class
are called, the thread enters a non-runnable mode.
• Thread returns from non-runnable state to runnable state and starts statement execution. The
thread dies when it exits the run() process. In Java, these thread state transformations are
referred to as the Thread life cycle.
• There are basically 4 stages in the lifecycle of a thread, as given below:
• New
• Runnable
• Running
• Blocked (Non-runnable state)
• Dead
• Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable.
Thread encapsulates a thread of execution.
• The Thread class defines several methods that help manage threads.
My first thread
14-09-2023 APP Faculties - CINTEL 24
Using the Thread Class: Thread(Runnable r, String
name)
public class MyThread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
t1.start();
t2.start();
}
} APP Faculties - CINTEL 27
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
• In this program, a reference to the current thread (the main thread, in this case) is
Example:
obtained by calling currentThread( ), and this reference is stored in the local variable
t.
• Next, the program displays information about the thread. The program then calls
setName( ) to change the internal name of the thread. Information about the thread is
then redisplayed.
• Next, a loop counts down from five, pausing one second between each line. The pause
is accomplished by the sleep( ) method.
• The argument to sleep( ) specifies the delay period in milliseconds. Notice the
try/catch block around this loop.
• This would happen if some other thread wanted to interrupt this sleeping one.
• This example just prints a message if it gets interrupted. In a real program, you would
need to handle this differently.
Output
APP Faculties - CINTEL 28
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Example that creates a new thread and starts it running
Output
APP Faculties - CINTEL 29
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Extending Thread (Continue…)
• The main thread to finish last. In the preceding examples, this is accomplished by calling sleep( ) within main( ), with a
long enough delay to ensure that all child threads terminate prior to the main thread.
• Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This method is
defined by Thread, and its general form is shown here:
• The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.
• While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called
join( ), shown here:
t1.start();
t2.start();
t1.setName(“Java thread");
System.out.println("After changing name of t1:"+t1.getName());
14-09-2023 APP Faculties - CINTEL 34
}
Example
Output
APP Faculties - CINTEL 36
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Thread Priorities
• Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
• To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form:
• Here, level specifies the new priority setting for the calling thread. The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.
• Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY,
which is currently 5. These priorities are defined as final variables within Thread.
• You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:
1. Class.forName()
2. DriverManager.registerDriver()
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())
Example:
Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost
:1521:xe,System,Pass123@)
There are 3 statement interfaces are available in the java.sql package. These are explained below:
a) Statement
This interface is used to implement simple SQL statements with no parameter. It returns the ResultSet object.
c) execute(String sql)
The execute() method is used to execute the SQL query. It returns true if it
executes the SELECT query. And, it returns false if it executes INSERT or
UPDATE query.
d) executeBatch()
This method is used to execute a batch of SQL queries to the Database and
if all the queries get executed successfully, it returns an array of update
APP Faculties - CINTEL 53
14-09-2023 Dr.Maivizhi counts.
Assistant We/ CINTEL
Professor will use this method to insert/update the bulk of records .
Retrieve Results
• When we execute the queries using the executeQuery() method, the result will be stored
in the ResultSet object.
• The returned ResultSet object will never be null even if there is no matching record in the
table. ResultSet object is used to access the data retrieved from the Database.
ResultSet rs 1= statemnt1.executeQuery(QUERY));
• The executeQuery() method for the SELECT query. When someone tries to execute the
insert/update query, it will throw SQLExecption with the message “executeQuery method
can not be used for update”.
• A ResultSet object points to the current row in the Resultset. To iterate the data in the
ResultSet object, call the next() method in a while loop. If there is no more record to read,
it will return FALSE.
• ResultSet can also be used to update data in DB. We can get the data from ResultSet using
getter methods such as getInt(), getString(), getDate(). We need to pass the column index
or column name as the parameter to get the values using Getter methods.
Learning Objectives:
• Introduction
CUI (Character User Interface)
GUI (Graphical User Interface)
Abstract Window Toolkit (AWT)
• What are Applets in Java?
Applet Basics
Life Cycle of an Applet
Types of Applets in Java
How to run an Applet
Sample Applet Programs
Advantages and Disadvantages
Applet Features over HTML
Whenever the end-user compile the program, can enter two numbers in the given space and clicking on the “equal button”, can get
the results in the specified space, which is easy to understand. This is an example for GUI for addition of two numbers.
14-09-2023
14-09-2023 Dr.Maivizhi Assistant Professor- CINTEL
APP Faculties / CINTEL 60
JAVA APPLETS
• Graphical User Interface (GUI)
Java Abstract Window Toolkit (AWT) is an Application Program Interface (API) to develop GUI or window-based
application in java. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous classes and methods
that allow you to create and manage the GUI window.
• Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser
or an applet viewer.
• Execution of an applet does not begin at main( ) [In other words, there is no main() method in an Applet]. Output to your
applet’s window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as
drawString( ), which outputs a string to a specified X,Y location. Input is also handled differently than in an application.
• Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a
Java-enabled web browser when it encounters the APPLET tag within the HTML file.
• To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that
contains the APPLET tag.
• An application is a standalone program that can be invoked from the command line.
• A servlet is a program that is invoked on demand on a server program and that runs in
the context of a web server process.
1.init( )
2.start( )
3.paint( )
1.stop( )
2.destroy( )
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
• public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.
Within the method paint() we will call the drawString() method to print a
text message in the applet window.
• Example:
<applet
codebase = “MyOwnApplet"
code = “FirstApplet.class"
width = 120
height = 120>
</applet>
• Example:
<applet
codebase = "http://www.myconnect.com/applets/"
code = "FirstApplet.class"
width = 120
height =120>
</applet>
There is no need to define the Applet's URL We need to define the Applet's URL in
in Local Applet. Remote Applet.
Local Applet is available on our computer. Remote Applet is not available on our
computer.
To use it or access it, we don't need Internet To use it or access it on our computer, we
Connection. need an Internet Connection.
It is written on our own and then embedded It was written by another developer.
into the web pages.
We don't need to download it. It is available on a remote computer, so we
need to download it to our system.
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code = “FirstApplet.class" width = "300" height = "200"></applet>
</body>
</html>
• In the HTML text file above, the code attribute of the <applet> tag specifies the applet class to execute.
• The width and height attributes are also required. They define the initial size of the panel on which the
applet is running.
• The applet command must be closed with the </applet> tag.
import java.applet.*;
import java.awt.*;
//FirstApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class FirstApplet extends Applet
{ To run an applet using the appletviewer tool, write in the
public void paint(Graphics g) command prompt:
{
g.drawString("welcome to my first applet",10,50); c:\>javac FirstApplet.java
} c:\>appletviewer FirstApplet.java
} c:\>appletviewer FirstApplet.html
Output:
• Text Fields
∙ Text area
∙ Labels
∙ Checkboxes
∙ Buttons
∙ Lists
∙ Drawing areas
∙ Menus
∙ Containers
Disadvantages of applets
• The client browser requires a plugin to run the applet.
• The mobile browser on iOS or Android does not run any Java applets. Desktop browsers have dropped support
for Java applets along with the rise of mobile operating systems.
Lightweight
JFC stands for Java Foundation Classes, a set of classes used to create graphical user
interfaces (GUIs) and add rich graphical features and interactivity to Java
applications.
JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package
javax.swing.JTextArea class. It is used for displaying multiple-line text.
Declaration:
public class JTextArea extends JTextComponent
Declaration:
public class JList extends JComponent implements Scrollable, Accessible
Syntax:
DefaultListModel<String> list1 = new DefaultListModel<>();
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList<String> list_1 = new JList<>(list1);
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 103
The JListContains 3 constructors. They are as follows:
JList()
JList(ary[] listData)
JList(ListModel<ary> dataModel)
Display:
Declaration:
public class JPopupMenu extends JComponent implements Accessible, MenuElement
Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");
Each of the components has a demarcated set of tasks which ensures smooth functioning of the entire
application along with complete modularity.
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ -CINTEL
Professor CINTEL 114
Model-View-Controller
Model :
• Model is where the application’s data objects are stored. It represents knowledge as a structure of
objects.
• The model doesn’t know anything about views and controllers but it can contain logic to update
controller if its data changes.
• The model is quite simply the data for our application.
• The data is “modelled” in a way it’s easy to store, retrieve, and edit.
• The model is how we apply rules to our data, which eventually represents the concepts our
application manages.
• For any software application, everything is modelled as data that can be handled easily.
• What is a user, a book, or a message for an app? Nothing really, only data that must be processed
according to specific rules. Like, the date must not be higher than the current date, the email must be
in the correct format, the name mustn’t be more than “x” characters long, etc.
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 115
Model-View-Controller
Model:
• Whenever a user makes any request from the controller, it contacts the appropriate model which
returns a data representation of whatever the user requested.
• This model will be the same for a particular work, irrespective of how we wish to display it to the
user.
• That is why we can choose any available view to render the model data.
• Additionally, a model also contains the logic to update the relevant controller whenever there is
any change in the model’s data.
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ -CINTEL
Professor CINTEL 118
Advantages of the MVC Architecture
• A common problem faced by application developers these days is the support for different type of
devices.
• The MVC architecture solves this problem as developers can create different interfaces for different
devices, and based on from which device the request is made, the controller will select an appropriate
view.
• The model sends the same data irrespective of the device being used, which ensures a complete
consistency across all devices.
• The MVC separation beautifully isolates the view from the business logic.
• It also reduces complexities in designing large application by keeping the code and workflow structured.
• This makes the overall code much easier to maintain, test, debug, and reuse.
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ -CINTEL
Professor CINTEL 123
Model-View-Controller
Step 4: Create the main Java file
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 125
Widgets
• Graphical User Interface (GUI) elements are the visual components that allow users to interact with
software applications.
• These elements are often referred to as "widgets," which are essentially building blocks that make up the
user interface.
• Each widget serves a specific purpose and provides a way for users to input information, view data, or
trigger actions. Here is a list of controls in the javax.swing package
Input Components
• Buttons ( JButton, JRadioButtons, JCheckBox)
• Text (JTextField, JTextArea)
• Menus (JMenuBar, JMenu, JMenuItem)
• Sliders (JSlider)
• JComboBox (uneditable) (JComboBox)
• List (Jlist )
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 126
Widgets
Information Display Components
• JLabel
• Progress bars (JProgressBar)
• Tool tips (using JComponent's setToolTipText(s) method)
Choosers
• File chooser (JFileChooser)
• Color chooser (JColorChooser)
More complex displays
• Tables (JTable)
• Trees (JTree)