16. Threads in Java
Non-Threaded Applications
Threaded Applications
Process based multitasking Vs Thread based multitasking
Thread API in Java
Creating Threads
States of a Thread
Synchronization for threads; static and non-static synchronized methods; blocks; concept of object and class locks
Coordination between threads - wait, notify and notifyAll methods for inter-thread communication
17. Applets
What are applets?
Need for Applets
Different ways of running an applet program
Applet API hierarchy
Life Cycle of an applet
Even Handlers for applets, mouse events, click events
18. Swing GUI
Introduction to AWT
Introduction to Swing GUI
Advantages of Swing over AWT
Swing API
Swing GUI Components
Event Handlers for Swing
Sample Calculator application using Swing GUI and Swing Event handling
19. JDBC
What is JDBC; introduction
JDBC features
JDBC Drivers
Setting up a database and creating a schema
Writing JDBC code to connect to DB
CRUD Operations with JDBC
Statement types in JDBC
Types of Rowset, ResultSet in JDBC
20. Access Modifiers in Java
What are access modifiers?
Default
Protected
Private
Public
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Access Modifiers in Java | Java Program
1. Java Class 6
“Don't worry if it doesn't work right [when coding]. If
everything did, you'd be out of a job.”
Agenda
•Threads in Java
•Applets
•Swing GUI
•JDBC
•Access Modifiers in Java
2. Java Values 2
What is a Thread?
•A thread is a lightweight sub-process, the smallest unit of
processing.
•Multiprocessing and multithreading, both are used to achieve
multitasking.
•Represents a separate path of execution of a group of
statements
•Java is the first language to include threading within the
language, rather than treating it as a facility of the OS
•Video Game example
1.one thread for graphics
2.one thread for user interaction
3.one thread for networking
•Server Example
1.Do various jobs
2.Handle Several Clients
Advantage:
1. Easier
2. better Performance
3. Multiple task
4.Share Resource
3. Java Values 3
Main Thread
Default Thread in any Java Program
JVM uses to execute program statements
Program To Find the Main Thread
Class Current
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);
System.out.println(“Name is: “+t.getName());
}
}
Output??
4. Threads in Java
Java Values 4
•Creating threads in Java:
1. Extend java.lang.Thread class
run() method must be overridden (similar to main method
of sequential program)
•run() is called when execution of the thread begins
•A thread terminates when run() returns
•start() method invokes run()
2. Implement java.lang.Runnable interface
Methods : run() , Start (), Sleep(), Wait (), Join(), getPriority()
, setPriority(), notify(), notifyall(),yield(),getname(), getid(),
isAlive(), currentthread(), isDaemon(),setDaemon() etc….
6. New
The thread is in new state if you create an instance of Thread
class but before the invocation of start() method.
Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the
running thread.
Running
The thread is in running state if the thread scheduler has
selected it
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently
not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method
exits. Java Values 6
7. Thread Priority
Each thread is assigned a default priority of
Thread.NORM_PRIORITY (constant of 5).
You can reset the priority using setPriority (int priority).
Some constants for priorities include:
o Thread.MIN_PRIORITY (1)
o Thread.MAX_PRIORITY (10)
Daemon thread in java is a service provider thread that
provides services to the user thread. Its life depend on the
mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
There are many java daemon threads running automatically
e.g. gc, finalizer etc.
setDaemon(); isDaemon() is a method used for daemon thread.
Java Values 7
8. Thread Synchronization
Java Values 8
•A shared resource may be corrupted if it is accessed
simultaneously by multiple threads.
•Example: two unsynchronized threads accessing the same
bank account may cause conflict.
• Known as a race condition in multithreaded programs.
•A thread-safe class does not cause a race condition in the
presence of multiple threads.
•Problem : race conditions
•Solution : give exclusive access to one thread at a time to code
that manipulates a shared object.
•It keeps other threads waiting until the object is available.
•The synchronized keyword synchronizes the method so that only
one thread can access the method at a time.
public synchronized void xMethod() {
// method body
}
obj
T1 (enter inside obj)
T2 (wait till T1 finish)
9. Deadlock
Apart of multithreading
Can occur when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is
acquired by first thread
Since, both threads are waiting for each other to release the lock, the
condition is called deadlock
Preventing Deadlock
Deadlock can be easily avoided by resource ordering.
With this technique, assign an order on all the objects whose locks must be
acquired and ensure that the locks are acquired in that order.
Example:
Thread 1: lock A lock B
Thread 2: wait for A lock C(when A is locked)
Thread 3: wait for A wait for B wait for C
Java Values 9
10. Inter-thread communication in Java
Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each other.
It is implemented by following methods of Object class:
wait()
notify()
notifyAll()
Java Values 10
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or
notifyAll() methods
after the specified amount of time, sleep
is completed.
11. Applets
Applet is a special type of program that is embedded in the
webpage to generate the dynamic content. It runs inside the
browser and works at client side.
Advantage of Applet
– It works at client side so less response time.
– Secured
– It can be executed by browsers running under many
plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
– Plugin is required at client browser to execute applet.
Java Values 11
12. 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.
Lifecycle of Java Applet
Java values
13. How to run an Applet?
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
Html file Example:
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Java Values 13
Output?
14. Swing GUI
What is Java Swing ?
• Part of the Java Foundation Classes (JFC)
• Provides a rich set of GUI components.
• Used to create a Java program with a graphical user
interface (GUI)
Features Of Swing
1) Java Look and Feel
2) Data Transfer
3) Internationalization and Localization
4) Accessibility
5) System Tray Icon Support
Java Values 14
15. Java Swing Components…
• Top Level Containers
• General Purpose Containers
• Special Purpose Containers
• Basic Controls
• Un-editable Information Displays
• Interactive Displays of Highly Formatted Information
Java Values 15
20. Implementing an Event Handler
• Implement the methods in the listener interface to
handle the event.
Conclusion
• You can use any helpful tools out there that are for
Java development like eclipse IDE, NetBeans IDE.
We will see all the swing component Examples while
doing Desktop application using Netbeans IDE.
Java Values 20
21. JDBC
Java Values 21
JDBC stands for Java Database Connectivity. JDBC is
a Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the
database.
Four types of JDBC drivers
1. JDBC-ODBC Bridge Driver,
2. Native Driver,
3. Network Protocol Driver, and
4. Thin Driver
22. Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and
execute the query with the database.
But, ODBC API uses ODBC driver which is written in C
language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program
and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
Java Values 22
23. Java Database Connectivity with 5 Steps
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("com.mysql.jdbc.Driver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
24. Statement interface
Java Values 24
1) public ResultSet executeQuery(String sql): is used to execute
SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute
specified query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries
that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of
commands.
•The Statement interface provides methods to execute
queries with the database.
•The statement interface is a factory of ResultSet i.e. it
provides factory method to get the object of ResultSet.
•Commonly used methods of Statement interface:
25. Java Values 25
JDBC RowSet
•The instance of RowSet is the java bean component
because it has properties and java bean notification
mechanism.
•It is introduced since JDK 5.
•It is the wrapper of ResultSet.
•It holds tabular data like ResultSet but it is easy and
flexible to use.
Advantage of RowSet
The advantages of using RowSet are
given below:
•It is easy and flexible to use
•It is Scrollable and Updatable by
default
26. Java Values 26
Statement PreparedStatement CallableStatement
It is used to execute normal
SQL queries.
It is used to execute
parameterized or dynamic
SQL queries.
It is used to call the stored
procedures.
It is preferred when a
particular SQL query is to
be executed only once.
It is preferred when a
particular query is to be
executed multiple times.
It is preferred when the
stored procedures are to be
executed.
You cannot pass the
parameters to SQL query
using this interface.
You can pass the
parameters to SQL query at
run time using this interface.
You can pass 3 types of
parameters using this
interface. They are – IN,
OUT and IN OUT.
This interface is mainly
used for DDL statements
like CREATE, ALTER,
DROP etc.
It is used for any
kind of SQL queries which
are to be executed multiple
times.
It is used to execute stored
procedures and functions.
The performance of this
interface is very low.
The performance of this
interface is better than the
Statement interface (when
used for multiple execution
of same query).
The performance of this
interface is high
27. Access Modifiers in Java
The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class.
We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
Java Values 27
28. Access Modifiers in Java
There are many non-access modifiers, such as
static, abstract, synchronized, native, volatile, transient, etc.
A class cannot be private or protected except nested class.
Java Values 28
Access
Modifier
within class within
package
outside
package by
subclass only
outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
29. Summary
Threads in Java
Process , Thread , Lifecycle of thread, Multithread,
communication between thread, Synchronization, priority
Daemon thread etc
Applets
what is applet, life cycle , and example and uses.
Swing GUI
Component, events, used and advantage
JDBC
Introduction, features,Drivers,Writing JDBC code to connect to DB,CRUD
Operations, Statement types ,Rowset, ResultSet
Access Modifiers in Java
Java Values 29
30. Java Values 30
Thank you !!!
GitHub Repository : https://github.com/eewsagar
YouTube: https://youtu.be/TBpu4Tlu7Q8
For any question please feel free to
comment.
Never
Assume
Clear it !!!