OOP Through Java UNIT-5 Material
OOP Through Java UNIT-5 Material
Multithreading
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
1. Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number ofmilliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.
2. Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling itchooses. 3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Joining threads
Sometimes one thread needs to know when another thread is ending. In java,
isAlive() and join() are two different methods to check whether a thread has finished its
execution.
The isAlive() methods return true if the thread upon which it is called is still running
otherwise it return false.
final booleanisAlive()
But, join() method is used more commonly than isAlive(). This method waits until the
thread on which it is called terminates.
final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specifid thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.
final void join(long milliseconds) throwsInterruptedException
Example of isAlive method
t2.start(); System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output
r1
true
true
r1
r2
r2
Example of thread without join() method
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
Output
r1
r1
r2 r1 r1 r2 r2
r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing
"r1" on console thread t1 goes to sleep for 500 mls.At the same time Thread t2 will start its
process and print "r1" on console and then goes into sleep for 500 mls. Thread t1 will
wake up from sleep and print "r2" on console similarly thread t2 will wake up from sleep
and print "r2" on console. So you will get output like
Example of thread with join() method
Output
r1
r2
r1
r2
In this above program join() method on thread t1 ensure that t1 finishes it process before
thread t2 starts.
Specifying time with join()
If in the above program, we specify time while using join() with m1, then m1 will execute
for that time, and thenm2 and m3 will join it.
m1.join(1500);
Doing so, initially m1 will execute for 1.5 seconds, after which m2 and m3 will join it.
In the last chapter we have seen the ways of naming thread in java. In this chapter we will
be learning the different priorities that a thread can have.
1. Logically we can say that threads run simultaneously but practically its not true,
only one Thread can run at a time in such a ways that user feels that concurrent
environment.
2. Fixed priority scheduling algorithm is used to select one thread for execution based
on priority.
Output :
Each thread has normal priority at the time of creation. We can change or modify the
thread priority in the following example 2.
5
5
Example#2: SettingPriority
package com.c4learn.thread;
public class ThreadPriority extends Thread
{
public void run() {
String tName = Thread.currentThread().getName();
Integer tPrio = Thread.currentThread().getPriority();
System.out.println(tName + " has priority " + tPrio);
}
public static void main(String[] args) throws InterruptedException
{
ThreadPriority t0 = new ThreadPriority();
ThreadPriorityt1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
t1.setPriority(Thread.MAX_PRIORITY);
t0.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t0.start();
t1.start();
t2.start();
}
}
Output :
4. At a time many thread can be ready for execution but the thread with highest
priority is selected for execution
Thread:PriorityandConstant
MIN_PRIORITY 1
MAX_PRIORITY 10
NORM_PRIORITY 5
JavaThreadSynchronization:
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication injava)
Mutual Exclusive
Mutual Exclusive helps keepthreads frominterfering with one another while sharing data.
This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock before accessing them, and then release
the lock when it's done with them.
Output: 5
10
15
20
25
100
200
300
400
500
Example of synchronized method by using annonymous class
In this program, we have created the two threads by annonymous class, so less coding is required.
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronizedblock.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
1. class Table {
2. void printTable(intn){
3. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
Output:5
10
15
20
25
100
200
300
400
500
1. class
Table{ 2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14. public class TestSynchronizedBlock2{
15. public static void main(String args[]){
16. finalTableobj = new Table();//only oneobject
18.
19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29. t1.start();
30. t2.start();
32. }
33. }
Output:5
10
15
20
25
100
200
300
400
500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In
case of synchronized method and synchronized block there cannot be interference
between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have
a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock.I want no interference between t1 and
t3 or t2 and t4.Static synchronization solves this problem.
Example of static synchronization
In this example we are applying synchronized keyword on the static method to perform
static synchronization.
1. class Table{
3. synchronized static void printTable(int){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12. class MyThread1 extends Thread{
13. public void run(){
14. Table.printTable(1);
16. }
17. }
18. class MyThread2 extends Thread{
19. public void run(){
20. Table.printTable(10);
22. }
23. }
24. class MyThread3 extends Thread{
25. public void run(){
26. Table.printTable(100);
28. }
29. }
30. class MyThread4 extends Thread{
31. public void run(){
32. Table.printTable(1000);
33. }
34. }
35. public classTestSynchronization4{
36. publicstaticvoid main(String t[]){
37. MyThread1 t1=new MyThread1();
38. MyThread2 t2=new MyThread2();
39. MyThread3 t3=new MyThread3();
40. MyThread4 t4=new MyThread4();
41. t1.start();
42. t2.start();
43. t3.start();
44. t4.start();
46. }
47. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Same example of static synchronization by annonymous class
In this example, we are using annonymous class to create the threads.
1. class Table
2. {
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12. public class TestSynchronization5 {
13. public static void main(String[]args){
14. Thread t1=new Thread(){
15. public void run(){
16. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27. Thread t3=new Thread(){
28.
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Synchronized block on a class lock:
The block synchronizes on the lock of the object denoted by the reference .class name
.class. A static synchronized method printTable(int n) in class Table is equivalent to the
following declaration:
Output:
Write a program to create and run a Thread
//creating and running a Thread
Write a program to create multiple threads and make the threads to act on single object
package Threads;
class Reserve implements Runnable
{
int available = 1;
int wanted;
Reserve (int i)
{
wanted = i;
}
public void run()
{
synchronized(this)
{
System.out.println ("Number of berths available: " + available);
if ( available >= wanted)
{
String name = Thread.currentThread().getName ();
System.out.println (wanted + " berths alloted to: " + name);
try {
Thread.sleep (2000); // wait for priniting the ticket printed
available = available - wanted; //zero
}
catch (InterruptedException ie)
{
ie.printStackTrace ();
}
}
else
{
System.out.println ("Sorry, no berths available");
}
}
}
}
Output:
Write a program to demonstrate the creation of thread group
//Using ThreadGroup import javaio*;
class WhyTGroups
{
public static void main (String args[]) throws IOException
{
Reservation res = new Reservation ();
Cancellation can = new Cancellation (); //Create a
ThreadGroup
ThreadGroup tg = new ThreadGroup ("Reservation Group");
//Create 2 threads and add them to thread group
Thread t1 = new Thread (tg, res, "First Thread");
Thread t2 = new Thread (tg, res, "Second Thread");
//Create another thread group as a child to tg
ThreadGroup tg1 = new ThreadGroup (tg, "Cancellation Group");
Thread t3 = new Thread (tg1, can, "Third Thread");
Thread t4 = new Thread (tg1, can, "Fourth Thread"); //find parent group of tg1
2) Using DriverManager.registerDriver
DriverManager class contains the following method which will load the driver at runtime.
public static void registerDriver (java.sql.Driver);
Driver is an interface which is implemented by various database vendors and server vendors. If
the appropriate driver object is created that driver object will act as a middle layer between program
and database. If the driver is not found we get an exception called java.sql.SQLException
For example:
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver);
[for oracle driver is – classes111.jar]
How to obtain the connection: After loading the drivers, it is required to obtain the connection
from the database.
Syntax or URL for obtaining connection:
Here, jdbc is the main protocol which takes java request and hand over into database environment
through Data Source Name. odbc is the sub protocol which takes the database result and gives to
java environment. Data Source Name is the configuration tool in the current working machine
through which the data is passing from java environment to database and database to java
environment.
Here, jdbc is the main protocol which takes java request and hand over into database environment
through Data Source Name. odbc is the sub protocol which takes the database result and gives to
java environment. Data Source Name is the configuration tool in the current working machine
through which the data is passing from java environment to database and database to java
environment.
In order to obtain the connection from the database, as a part of jdbc we have a predefined
class called java.sql.DriverManager which contains the following methods:
1. public static Connection getConnection (String URL);
2. public static Connection getConnection (String URL, String username, String password);
Method-1, we use to obtain the connection from those databases where there is no
username and password databases. Method-2 is used for those databases where there is username
and password.
For example:
Connection con1=DriverManager.getConnection (“jdbc : odbc : Access”);
Connection con2=DriverManager.getConnection (“jdbc : odbc : oracle”,”scott”,”tiger”);
Pass the query: A query is nothing but a request or question to the database.
Queries are of three types; they are
1. static query,
2. dynamic or pre-compiled query
3. stored procedures
STATIC QUERY: Static query is one in which the data is passed in the query itself.
For example:
1. select * from Student where marks>50;
2. insert into Student values (100, ‘abc’, 90.86);
In order to execute static queries we must obtain an object of java.sql.Statement interface.In the
interface java.sql.Connection we have the following method for obtaining an object of Statement
interface.
For example:
Statement st = con1.createStatement ();
On database three categories of operations takes place, they are insertion, deletion and updation.
In order to perform these operations we must use the following method which is present in
statement interface.
Here, String represents either static insertion or static deletion or static updation. The return type
int represents the status of the query. If the query is not successful it returns zero and if the query
is successful it returns non-zero.
Here, String represents a query which contains select statement. executeQuery returns an object
of ResultSet to hold the number of records returned by select statement. ResultSet is an interface
whose object contains all the records returned by a query and it will point to just before the first
record.
For example:
ResultSet rs=st.executeQuery (“select * from Student”);
The ResultSet object is pointing by default just before the first record, in order to bring first
record we must use the below given method. Method returns true when rs contains next record
otherwise it returns false.
public boolean next ();
In order to obtain the data of the record (collection of field values) we must use the following
method:
public String getString (int colno);
Whatever the data retrieving from the record that data will be treated as string data.
For example:
String s1=rs.getString (1);
String s1=rs.getString (2);
String s1=rs.getString (3);
ResultSet:
1. An object of ResultSet allows us to retrieve the data by default only in forward direction but not
in backward direction and random retrieval.
2. Whenever we get the database data in ResultSet object which will be temporarily disconnected
from the database.
3. ResultSet object does not allows us to perform any modifications on ResultSet object.
4. Hence, the ResultSet is by default non-scrollable disconnected ResultSet.
In order to set the values to the positional parameters, we must use the following methods which are
present in prepared statement interface.
public void setByte (int, byte);
public void setShort (int, short);
public void setInt (int, int);
public void setLong (int, long);
public void setFloat (int, float);
public void setDouble (int, double);
public void setChar (int, char);
public void setString (int, string);
In general PreparedStatement interface contains the following generalized method to set the
values for positional parameters.
public void setXXX (int, XXX);
Here, int represents position number of the positional parameter. XXX represents value of
either fundamental data type or string or date.
For example:
ps.setInt (1, 10);
In order to execute the DCL statements (select) and DML statements (insert, delete and update)
we must use the following methods which are present in PreparedStatement interface.
public int executeUpdate (); _ Dynamic DML/DDL
public ResultSet executeQuery (); _ Dynamic DCL (select)
For example:
ResultSet rs=ps.executeQuery ();
Close connection
For example:
con.close ();
Advantages:
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages:
1. Performance overhead since the calls have to go through the JDBC overhead bridge to the
ODBC driver, then to the native database connectivity interface.
2. The ODBC driver needs to be installed on the client machine.
3. Considering the client-side software needed, this might not be suitable for applets.
Type 2 Driver:
Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database library API.
This driver converts the JDBC calls into a database specific call for databases such as SQL,
ORACLE etc. This driver communicates directly with the database server. It requires some native
code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type
1 drivers, Type 2 drivers require native database client libraries to be installed and configured on
the client machine.
Functions:
1. This type of driver converts JDBC calls into calls to the client API for that database.
2. Client -> JDBC Driver -> Vendor Client DB Library -> Database
Advantage:
Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
1. The vendor client library needs to be installed on the client machine.
2. Cannot be used in internet due the client side software needed
3. Not all databases give the client side library.
Advantages
1. Since the communication between client and the middleware server is database independent,
there is no need for the vendor db library on the client machine. Also the client to middleware
needn’t be changed for a new database.
2. The Middleware Server (Can be a full-fledged J2EE Application server) can provide typical
middleware services like caching (connections, query results, and so on), load balancing, logging,
auditing etc.
3. eg. For the above include jdbc driver features in WebLogic.
4. Can be used in internet since there is no client side software needed.
5. At client side a single driver can handle any database. (It works provided the middleware
supports that database!!)
Disadvantages
1. Requires database-specific coding to be done in the middle tier.
2. An extra layer added may result in a time-bottleneck. But typically this is overcome by providing
efficient middleware services described above.
Functions
1. Type 4 drivers are entirely written in Java that communicate directly with a vendor's database
through socket connections. No translation or middleware layers, are required, improving
performance.
2. The driver converts JDBC calls into the vendor-specific database protocol so that client
applications can communicate directly with the database server.
3. Completely implemented in Java to achieve platform independence.
4. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect
to jdbc:oracle:thin URL format.
5. Client Machine -> Native protocol JDBC Driver -> Database server
Advantages
These drivers don't translate the requests into db request to ODBC or pass it to client API for the
db, nor do they need a middleware layer for request indirection. Thus the performance is
considerably improved.
Disadvantage
At client side, a separate driver is needed for each database
An Example Diagram
Java JDBC: Interaction of the core JDBC components during the execution of a database query.
JDBC Driver
A JDBC driver translates standard JDBC calls into a network or database protocol or into a
database library API call that facilitates communication with the database. This translation layer
provides JDBC applications with database independence. If the back-end database changes, only
the JDBC driver need be replaced with few code modifications required.
Java Program:
import java.sql.*;
public class DBExample
{
public static void main(String[] args) throws SQLException
{
String url="jdbc:ucanaccess://C://Users//Ajay007//Desktop//JAVA
PROGRAMS//DBProject//GIET.accdb";
Connection con=DriverManager.getConnection(url);
System.out.println("Connected to MS Access Database");
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("Select * from Student");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)+"\t\t
"+rs.getString(3)+"\t\t"+rs.getString(4));
}
}
Output:
}
});
b1.setFont(new Font("Tahoma", Font.PLAIN, 16));
b1.setBounds(256, 233, 200, 29);
contentPane.add(b1);
Java Program:
Output:
Oracle Database Query:
Unit-5
Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image,
event handling.
1. JavaFX GUI: Introduction
JavaFX is a framework for building graphical user interfaces (GUIs) in Java. It is used to create modern,
feature-rich applications with a wide range of components like buttons, text fields, images, and event-driven
functionalities. JavaFX has replaced the older Swing framework for building GUIs in Java.
This brief overview covers essential aspects of working with JavaFX GUIs, including building interfaces
with Scene Builder, displaying content like text and images, and handling events to make applications
interactive.