Java Multithreading Overview and Concepts
Java Multithreading Overview and Concepts
MULTITHREADING
MULTITHREADING
• Java provides builtin support for multithreaded programming.
• 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.
TYPES OF MULTITASKING
Processbased Multitasking
• A process is, in essence, a program that is executing.
• Thus, processbased multitasking is the feature that allows your computer to run two or
more programs concurrently.
• Ex: Processbased multitasking enables you to run the Java compiler at the same time that you
are using a text editor.
Threadbased Multitasking
• In a threadbased multitasking environment, the thread is the smallest unit of dispatchable code.
• This means that a single program can perform two or more tasks simultaneously.
• Ex: 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.
1
• In this model, a single thread of control runs in an infinite loop, polling a single event
queue to decide what to do next.
• Once this polling mechanism returns with, say, a signal that a network file is ready to be read,
then the event loop dispatches control to the appropriate event handler.
• Until this event handler returns, nothing else can happen in the system.
• This wastes CPU time. It can also result in one part of a program dominating the system
and preventing any other events from being processed.
• In general, in a singledthreaded environment, when a thread blocks (that is, suspends
execution) because it is waiting for some resource, the entire program stops running.
Java’s Multithreading System
• The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated.
• One thread can pause without stopping other parts of your program.
• For example, the idle time created when a thread reads data from a network or waits for
user input can be utilized elsewhere.
• Multithreading allows animation loops to sleep for a second between each frame without
causing the whole system to pause.
• When a thread blocks in a Java program, only the single thread that is blocked pauses.
• All other threads continue to run.
THREADS
Threads exist in several states.
Running
Ready to
Run
Suspended
Resumed
Blocked
Terminated
Method Meaning
3
Program 1
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = [Link]();
[Link]("Current thread: " + t);
[Link]("My Thread");
[Link]("After name change: "
+ t); try
{
for(int n = 5; n > 0; n)
{
[Link](n);
[Link](1000);
}
}
catch (InterruptedException e)
{
[Link]("Main thread interrupted");
}
}
}
Sleep()
• The sleep( ) method causes the thread from which it is called to suspend execution for
the specified period of milliseconds.
Its general form is shown here:
static void sleep(long milliseconds) throws InterruptedException
Creating a Thread
• You create a thread by instantiating an object of type Thread.
• Java defines two ways in which this can be accomplished:
■ You can implement the Runnable interface.
■ You can extend the Thread class, itself.
Implementing Runnable
• The easiest way to create a thread is to create a class that implements the Runnable interface.
• You can construct a thread on any object that implements Runnable.
• To implement Runnable, a class need only implement a single method called run( ), which is
4
declared like this:
public void run( )
• run( ) establishes the entry point for another, concurrent thread of execution within
your program.
• This thread will end when run( ) returns.
Program 4
7
• Program 5
[Link](1000);
}
} catch (InterruptedException e)
{ [Link](name + "
interrupted.");
}
[Link](name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new
NewThread("Three");
[Link]("Thread One is alive: "
+ [Link]());
8
[Link]("Thread Two is alive:
" + [Link]());
[Link]("Thread Three is alive:
" + [Link]());
// wait for threads to
finish try {
[Link]("Waiting for threads to
finish."); [Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread
Interrupted");
}
[Link]("Thread One is alive: "
+ [Link]());
[Link]("Thread Two is alive:
" + [Link]());
[Link]("Thread Three is alive:
" + [Link]());
[Link]("Main thread exiting.");
}
}
Thread Priorities
• Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run.
• A higherpriority thread can also preempt a lowerpriority one.
• For Example, when a lowerpriority thread is running and a higherpriority thread resumes
(from sleeping or waiting on I/O, for example), it will preempt the lowerpriority thread.
• To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is
its general form:
final void setPriority(int level)
• The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
• Currently, these values are 1 and 10, respectively.
[Link]()
; try {
[Link](10000);
} catch (InterruptedException e) {
[Link]("Main thread
interrupted.");
}
[Link]();
[Link]();
// Wait for child threads to
terminate. try {
[Link]();
10
[Link]();
} catch (InterruptedException e) {
[Link]("InterruptedException
caught");
}
[Link]("Lowpriority thread: " +
[Link]); [Link]("Highpriority thread: "
+ [Link]);
}
}
Synchronization
• When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time.
• The process by which this is achieved is called synchronization.
• Key to synchronization is the concept of the monitor (also called a semaphore).
Monitor
• A monitor is an object that is used as a mutually exclusive lock, or mutex.
• 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.
• These other threads are said to be waiting for the monitor.
• A thread that owns a monitor can reenter the same monitor if it so desires.
Java implements synchronization through language elements in either one of the two ways.
1. Using Synchronized Methods
2. The synchronized Statement
Using Synchronized Methods
Program 7(unsynchronized
Thread) class Callme {
void call(String msg) {
[Link]("[" +
msg); try {
[Link](1000);
} catch(InterruptedException e)
{
[Link]("Interrupted"
);
11
}
[Link]("]");
}
}
class Caller implements Runnable
{ String msg;
Callme
target;
Thread t;
public Caller(Callme targ, String
s) { target = targ;
msg = s;
t = new
Thread(this);
[Link]();
}
public void run() {
[Link](msg);
}
}
class Synch {
public static void main(String
args[]) { Callme target = new
Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target,
"Synchronized"); Caller ob3 = new
Caller(target, "World");
// wait for threads to
end try {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e)
{
[Link]("Interrupted"
);
}
}
}
12
The synchronized Statement
• Second solution is to call the methods defined by the class inside a synchronized block.
• This is the general form of the synchronized statement:
synchronized(object)
{
// statements to be synchronized
}
Program 8
class Callme
{
void call(String msg) {
[Link]("[" +
msg); try {
[Link](1000);
} catch (InterruptedException e)
{
[Link]("Interrupted"
);
}
[Link]("]");
}
}
class Caller implements Runnable
{ String msg;
Callme
target;
Thread t;
public Caller(Callme targ, String
s) { target = targ;
msg = s;
t = new
Thread(this);
[Link]();
}
// synchronize calls to
call() public void run() {
synchronized(target) { // synchronized
block [Link](msg);
13
}
}
}
class Synch1 {
public static void main(String
args[]) { Callme target = new
Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target,
"Synchronized"); Caller ob3 = new
Caller(target, "World");
// wait for threads to end
try {
[Link]()
;
[Link]()
;
[Link]()
;
} catch(InterruptedException e)
{
[Link]("Interrupted"
);
}
}
}
Interthread Communication
• To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ),
notify( ), and notifyAll( ) methods.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest
priority thread will run first.
These methods are declared within Object, as shown
here: final void wait( ) throws
InterruptedException final void notify( )
final void notifyAll( )
Program 9 (Correct Implementation of Producer & Consumer Problem)
class Q {
14
int n;
boolean valueSet =
false; synchronized int
get() { if(!valueSet)
try {
wait(
);
} catch(InterruptedException e) {
[Link]("InterruptedException
caught");
}
[Link]("Got: " + n);
valueSet =
false; notify();
return n;
}
synchronized void put(int n)
{ if(valueSet)
try {
wait(
);
} catch(InterruptedException e) {
[Link]("InterruptedException
caught");
}
this.n = n;
valueSet =
true;
[Link]("Put: " +
n); notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q)
{ this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{ int i = 0;
while(true) {
15
[Link](i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q)
{ this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{ while(true) {
[Link]();
}
}
}
class PCFixed {
public static void main(String
args[]) { Q q = new Q();
new Producer(q);
new
Consumer(q);
[Link]("Press ControlC to stop.");
}
}
16
Deadlock
• A special type of error that you need to avoid that relates specifically to multitasking is
“deadlock”.
• It occurs when two threads have a circular dependency on a pair of synchronized objects.
Deadlock is a difficult error to debug for two reasons:
■ In general, it occurs only rarely, when the two threads timeslice in just the right way.
■ It may involve more than two threads and two synchronized objects.
Suspending, Resuming, and Stopping Threads
• suspend( ) and resume( ), which are methods defined by Thread, to pause and
restart the execution of a thread. They have the form shown below:
final void
suspend( )
final void
resume( )
• The Thread class also defines a method called stop( ) that stops a thread. Its
signature is shown here:
final void stop( )
The String class is defined in the [Link] package and hence is implicitly available to all the
programs in Java. The String class is declared as final, which means that it cannot be subclassed.
It extends the Object class and implements the Serializable, Comparable, and CharSequence
interfaces.
Java implements strings as objects of type String. A string is a sequence of characters. Unlike
most of the other languages, Java treats a string as a single value rather than as an array of
characters.
The String objects are immutable, i.e., once an object of the String class is created, the string it
contains cannot be changed.
In other words, once a String object is created, the characters that comprise the string cannot be
changed. Whenever any operation is performed on a String object, a new String object will be
created while the original contents of the object will remain unchanged.
17
However, at any time, a variable declared as a String reference can be changed to point to some
other String object.
Though there could be many possible answer for this question and only designer of String class
can answer this, I think below three does make sense
1) Imagine StringPool facility without making string immutable, its not possible at all because in
case of string pool one string object/literal e.g. "Test" has referenced by many reference variables
, so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A
will also be "TEST" which is not desirable.
2) String has been widely used as parameter for many java classes e.g. for opening network
connection you can pass hostname and port number as string , you can pass database URL as
string for opening database connection, you can open any file by passing name of file as
argument to File I/O classes.
In case if String is not immutable, this would lead serious security threat , I mean some one can
access to any file for which he has authorization and then can change the file name either
deliberately or accidentally and gain access of those file.
3) Since String is immutable it can safely shared between many threads, which is very
important for multithreaded programming.
String
Strings: A String represents group of characters. Strings are represented as String objects
in java.
Creating Strings:
➢ We can declare a String variable and directly store a String literal using assignment
operator.
18
String str = "Hello";
➢ We can create String object using new operator with some data.
➢ We can create a String by passing array name and specifying which characters we need:
Here starting from 2nd character a total of 3 characters are copied into String s3.
19
String represents a sequence of characters. It has fixed length of character sequence.
Once a string object has been created than we can't change the character that comprise
that string. It is immutable. This allows String to be shared. String object can be
instantiated
Accessor methods:
length(),
charAt(i),
getBytes(),
getChars(istart,iend,gtarget[],itargstart),
split(string,delim),
toCharArray(),
Modifier methods:
concat(g),
replace(cWhich, cReplacement),
toLowerCase(),
toUpperCase(),
trim().
20
Modifying a String
The String objects are immutable. Therefore, it is not possible to change the original contents of
a string. However, the following String methods can be used to create a new copy of the string
with the required modification:
substring()
The substring() method creates a new string that is the substring of the string that invokes the
method. The method has two forms:
where, startindex specifies the index at which the substring will begin and endindex specifies the
index at which the substring will end. In the first form where the endindex is not present, the
substring begins at startindex and runs till the end of the invoking string.
Concat()
The concat() method creates a new string after concatenating the argument string to the end of
the invoking string. The signature of the method is given below:
replace()
The replace() method creates a new string after replacing all the occurrences of a particular
character in the string with another character. The string that invokes this method remains
unchanged. The general form of the method is given below:
trim()
The trim() method creates a new copy of the string after removing any leading and trailing
whitespace. The signature of the method is given below:
toUpperCase()
21
The toUpperCase() method creates a new copy of a string after converting all the lowercase
letters in the invoking string to uppercase. The signature of the method is given below:
toLowerCase()
The toLowerCase() method creates a new copy of a string after converting all the uppercase
letters in the invoking string to lowercase. The signature of the method is given below:
Searching Strings
The String class defines two methods that facilitate in searching a particular character or
sequence of characters in a string. They are as follows:
IndexOf()
The indexOf() method searches for the first occurrence of a character or a substring in the
invoking string. If a match is found, then the method returns the index at which the character or
the substring first appears. Otherwise, it returns -1.
lastIndexOf()
The lastIndexOf() method searches for the last occurrence of a character or a substring in the
invoking string. If a match is found, then the method returns the index at which the character or
the substring last appears. Otherwise, it returns –1.
22
Program : Write a program using some important methods of String class.
class StrOps
[Link] ();
if ([Link] (str2) )
else
if ([Link] (str3) )
else
else
idx = [Link]("One");
StringBuffer
StringBuffer: StringBuffer objects are mutable, so they can be modified. The methods that
directly manipulate data of the object are available in StringBuffer class.
Creating StringBuffer:
➢ We can create a StringBuffer object by using new operator and pass the string to the
object, as: StringBuffer sb = new StringBuffer ("Kiran");
➢ We can create a StringBuffer object by first allotting memory to the StringBuffer
object using new operator and later storing the String into it as:
[Link] (“Kiran”);
This represents growable and writeable character sequence. It is mutable in nature. StringBuffer
are safe to be used by multiple thread as they are synchronized but this brings performance
penalty.
It defines 3-constructor:
• StringBuffer(); //initial capacity of 16 characters
• StringBuffer(int size); //The initial size
• StringBuffer(String str);
import [Link].*;
class Mutable
25
{ // to accept data from keyboard
String sur=[Link] ( );
String mid=[Link] ( );
String last=[Link] ( );
[Link] (sur);
[Link] (last);
int n=[Link] ( );
26
JavaFX is a Java library and a GUI toolkit designed to develop and facilitate Internet
applications, web applications, and desktop applications.
JavaFX Scene Builder is a visual layout tool that lets users quickly design JavaFX
application user interfaces, without coding. Users can drag and drop UI components to a
work area, modify their properties, apply style sheets, and the FXML code for the layout
that they are creating is automatically generated in the background.
The result is an FXML file that can then be combined with a Java project by binding the
UI to the application’s logic.
o
o public void init()
o public abstract void start(Stage primaryStage)
o public void stop()
in order to create a basic JavaFX application, we need to:
The [Link] class is used to load an image into a JavaFX application. This supports
BMP, GIF, JPEG, and, PNG formats.
JavaFX provides a class named [Link] is a node that is used to display, the
loaded image.
27
• Instantiate the Image class bypassing the input stream object created above, as a parameter to
its constructor.
• Set the image to it by passing above the image object as a parameter to the setImage() method.
• Set the required properties of the image view using the respective setter methods.
Example
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
28
//Creating the image view
[Link](image);
[Link](10);
[Link](10);
[Link](575);
[Link](true);
[Link]("Displaying Image");
[Link](scene);
[Link]();
launch(args);
29
Event and Listener (Java Event Handling)
For example, click on button, dragging mouse etc. The [Link] package provides
many event classes and Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
Various mehods for MouseEvent class are enlisted in the following table
30
Connecting to DB
What is JDBC
Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with
your database server.
For example, using JDBC drivers enable you to open database connections and to interact
with it
31
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and sonoo is the database name. We may use any database, in such
case, you need to replace the sonoo with your database name.
4. Password: Password is given by the user at the time of installing the mysql database.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
In this example, sonoo is the database name, root is the username and password.
import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
JDBC-Result Sets
The SQL statements that read data from a database query, return the data in a result set.
The SELECT statement is the standard way to select rows from a database and view them
in a result
set. The [Link] interface represents the result set of a database query.
32
A ResultSet object maintains a cursor that points to the current row in the result set. The
term "result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
Navigational methods: Used to move the cursor around.
Get methods: Used to view the data in the columns of the current row being pointed
by
the cursor.
Update methods: Used to update the data in the columns of the current row. The
updates
can then be updated in the underlying database as well.
33