0% found this document useful (0 votes)
25 views30 pages

Java Multithreading Basics Explained

Multithreading in Java allows multiple threads to execute simultaneously, enhancing performance and user experience. The lifecycle of a thread includes states such as New, Runnable, Running, Non-Runnable, and Terminated, with methods to create and manage threads. Synchronization is crucial for controlling access to shared resources, and Java provides mechanisms like synchronized methods, blocks, and inter-thread communication through wait and notify methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views30 pages

Java Multithreading Basics Explained

Multithreading in Java allows multiple threads to execute simultaneously, enhancing performance and user experience. The lifecycle of a thread includes states such as New, Runnable, Running, Non-Runnable, and Terminated, with methods to create and manage threads. Synchronization is crucial for controlling access to shared resources, and Java provides mechanisms like synchronized methods, blocks, and inter-thread communication through wait and notify methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Multithreading in java

is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing.

Advantages of Java Multithreading


1) It doesn't block the user because threads are
independent and you can perform multiple operations
at same time.

2) You can perform many operations together so it


saves time.

3) Threads are independent so it doesn't affect


other threads if exception occur in a single
.thread.
Life cycle of a Thread
The life cycle of the thread in java is controlled by JVM. The
java thread states are as follows:

1) New
▶ The thread is in new state if you create an instance of Thread
class but before the invocation of start() method.

2) 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.

3) Running

▶ The thread is in running state if the thread scheduler


has selected it.

4) Non-Runnable (Blocked)

▶ This is the state when the thread is still alive, but is


currently not eligible to run.

5) Terminated
▶ A thread is in terminated or dead state when its run()
method exit.
How to create thread
By extending Thread class
By implementing Runnable interface.
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.

Commonly used Constructors of Thread class:


1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
Thread can be created in two ways
1)by extending Thread class
2)by implementing Runnable interface

1)by extending Thread class


class A extends Thread
{
public void run()
{

for (int i=0;i<=5;i++) [Link](i);


}
}
class ThreadDemo

public static void main (String args[])

A oba = new A();

[Link]();

}
2)by implementing Runnable interface

class A implements Runnable{

public void run()

for (int i=0;i<=5;i++)

[Link](i);
}
}
Class Test{

public static void main(String args[]){

A m=new A();

Thread t=new Thread(m);

[Link]();
}

Common methods of thread class

▶ public void run(): is used to perform action for a thread.


▶ public void start(): starts the execution of the [Link] calls
the run() method on the thread.
▶ public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.
▶ public void join(): waits for a thread to die.
▶ public void join(long miliseconds): waits for a thread to die
for the specified miliseconds.
▶ public int getPriority(): returns the priority of the thread.
▶ public int setPriority(int priority): changes the priority of
the thread.
▶ public String getName(): returns the name of the thread.
▶ public void setName(String name): changes the name of the
thread.

Main Thread
class CurrentThreadDemo {
public static void main(String args[])

[Link]([Link]());

Output
Thread[main,5,main]

isAlive() and join()

isAlive()
▶ The isAlive( ) method returns true if the thread upon which it is called is
still running. It returns false otherwise
final boolean isAlive( )

join()
▶ This method waits until the thread on which it is called terminates. Its name
comes from the concept of the calling thread waiting until the specified
thread joins it.
▶ Additional forms of join( ) allow you to specify a maximum amount of
time that you want to wait for the specified thread to terminate.
final void join( ) throws InterruptedExceptio
Thread Priorities

▶ Thread priorities are used by the thread scheduler to decide when each
thread should be allowed to run.

In practice, the amount of CPU time that a thread gets often depends on several factors besides its
priority. (For example, how an operating system implements multitasking can affect the relative
availability of CPU time.) A higher-priority thread can also preempt a lower-priority one. For
instance, when a lower-priority thread is running and a higher-priority thread resumes (from
sleeping or waiting on I/O, for example), it will preempt the lower- priority thread.

setPriority()
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)

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 static final variables within
Thread.
getPriority()

▶ You can obtain the current priority setting by calling the


getPriority( ) method of Thread :

▶ final int getPriority( )


synchronizing threads
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
When we want to share the resource with multiple threads, we can use the Java
synchronization concept. So there is a need to synchronize the action of multiple threads
and make sure that onlyone thread can access the resource at a given point in time. This is
implemented using a concept called monitors. Each object in Java is associated with a
monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a
monitor.

Purpose of using synchronization


1. To prevent thread interference
2. To prevent consistency problem
Types of Thread synchronization
There are two types of thread synchronization mutual exclusiveand inter-thread
communication.
Mutual Exclusive
1. Synchronized method.

2. Synchronized block.
3. static synchronization.
Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways injava:
by synchronized method
by synchronized block
by static synchronization

Synchronized Method
If you declare any method as synchronized, it is known assynchronized
method. Synchronized method is used to lock an
object for any shared resource. When a thread invokes a synchronized method,
it automatically acquires the lock for thatobject and releases it when the thread
completes its task.
class Test1
{

synchronized public void display()


{

for(int i=1;i<=5;i++)
{

[Link](i);

}}
class Pa2 extends Thread
{
Test1 t1;
Pa2(Test1 t)
{
t1=t;
}
public void run()
{
[Link]();
}
}
class Pa2 extends Thread

Test1 t;
Pa2(Test1 t)
{
this.t=t;
}
public void run()
{
[Link]();
}

}
public class sync {
public static void main(String args[]) {
Test1 t=new Test1();

Pa1 p1=new Pa1(t);

Pa2 p1=new Pa2(t);

[Link]();

[Link]();
}
}

Synchronized Block
Synchronized block can be used to perform synchronization on anyspecific resource
of the [Link] you have 50 lines of codein your method, but you want to
synchronize only 5 lines, you can use synchronized [Link] you put all the codes of
the method in the synchronized block, it will work same as the synchronized method.

Purpose of Synchronized Block


1. Synchronized block is used to lock an object for any sharedresource.
2. Scope of synchronized block is smaller than the method.

Syntax:
synchronized (object reference expression)
{
//code block
}
Prgoram
class Test1
{

public void display()


{

Synchronized(this){

for(int i=1;i<=5;i++)
{

[Link](i);
}

}}}
class Pa2 extends Thread
{
Test1 t1;
Pa2(Test1 t)
{
t1=t;
}
public void run()
{
[Link]();
}
}
class Pa2 extends Thread

Test1 t;
Pa2(Test1 t)
{
this.t=t;
}
public void run()
{
[Link]();
}

}
public class sync {
public static void main(String args[]) {
Test1 t=new Test1();

Pa1 p1=new Pa1(t);

Pa2 p1=new Pa2(t);

[Link]();

[Link]();
}
}
Static Synchronization Block
If you make any static method as synchronized, the lock will be onthe class not on
object.
class Test1
{
Synchronized static public void display()
{

for(int i=1;i<=5;i++)
{

[Link](i);

}}
class Pa2 extends Thread
{
Test1 t1;
Pa2(Test1 t)
{
t1=t;
}
public void run()
{
[Link]();
}
}
class Pa2 extends Thread

Test1 t;
Pa2(Test1 t)
{
this.t=t;
}
public void run()
{
[Link]();
}

}
public class sync {
public static void main(String args[]) {
Test1 t=new Test1();

Pa1 p1=new Pa1(t);

Pa2 p1=new Pa2(t);


[Link]();

[Link]();
}
}

Inter-thread Communication
Polling is a process in which the condition is repeatedly checked. If thecondition is true,
appropriate action is taken. This wastes CPU time.

For example, consider the classic queuing problem, where one thread is producing some data and
another is consuming it. To make the problem more interesting, suppose that the producer has to
wait until the consumer is finished before it generates more data. In a polling system, the
consumer would waste many CPU cycles while it waited for the producer to produce. Once the
producer was finished, it would startpolling, wasting more CPU cycles waiting for the consumer to
finish, and so on.

To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ),
notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so
all classes have them. All three methods can be called only from within a synchronized context.
• 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 a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.

The following methods are declared within Object: final void wait( )
throws InterruptedExceptionfinal void notify( )
final void notifyAll( )

Example Program:
class Test1
{

synchronized void display()


{

for(int i=1;i<=5;i++)
{
[Link](i);
}
notify();

}
class Pa1 extends Thread
{
Test1 t;
Pa1(Test1 t)
{
this.t=t;
}
public void run()
{
[Link]();
}

}
class Pa2 extends Thread
{
Test1 t1;
Pa2(Test1 t)
{
t1=t;
}
public void run()
{
[Link]();
}
}
public class ProgA {
public static void main(String args[])
{
Test1 t=new Test1();
Pa1 p1=new Pa1(t);
Pa2 p2=new Pa2(t);
[Link]();
[Link]();
synchronized(p2)
{
try {
[Link]();
} catch (Exception ex) {

}
}
}
}
ENUMERATIONS
 “Enumeration means a list of named constant, enum in java is a data type that
contains fixed set of constants.
 It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc.
 It is available from JDK 1.5.
 An Enumeration can have constructors, methods and instance variables. It is created
using enum keyword.
 Each enumeration constant is public, static and final by default.
 Even though enumeration defines a class type and have constructors, you do not
instantiate an enum using new.
 Enumeration variables are used and declared in much a same way as you do a
primitive variable.

ENUMERATION FUNDAMENTALS

How to Define and Use an Enumeration


 An enumeration can be defined simply by creating a list of enum variable. Let us take
an example for list of Subject variable, with different subjects in the list.

enum Subject //Enumeration defined


{
JAVA, CPP, C, DBMS
}

 Identifiers JAVA, CPP, C and DBMS are called enumeration constants. These are
public, static and final by default.
 Variables of Enumeration can be defined directly without any new keyword.

Ex: Subject sub;

 Variables of Enumeration type can have only enumeration constants as value.


 We define an enum variable as: enum_variable = enum_type.enum_constant;
Ex: sub = [Link];
 Two enumeration constants can be compared for equality by using the = = relational
operator.
Example:
if(sub == [Link])
{
...
}

Program 1: Example of Enumeration


Enum Days
{
Monday,Tuesday;
}
class Test
{
public static void main(String args[])
{
[Link]([Link]);
}
}
Output : Monday

Or
Enum Days
{
Monday,Tuesday;
}
class Test
{
public static void main(String args[])
{
Days d=[Link];
[Link](d);
}
}
Output : Monday
values() and valueOf() Methods
 The java compiler internally adds the values() method when it creates an enum.
 The values() method returns an array containing all the values of the enum.
 Its general form is,
public static enum-type[ ] values()
 valueOf() method is used to return the enumeration constant whose value is equal
tothe string passed in as argument while calling this method.
 It's general form is,
public static enum-type valueOf (String str)

Program 3: Example of enumeration using values() and valueOf() methods:

values()
Enum Days
{
Monday,Tuesday;
}
class Test
{
public static void main(String args[])
{
Days d[]=[Link];
[Link](d[0]);
}
}
Output : Monday

Enum Days
{
Monday,Tuesday;
}
class Test
{
public static void main(String args[])
{

[Link]([Link](“Monday”));
}
}
Output : Monday

Points to remember about Enumerations


1. Enumerations are of class type, and have all the capabilities that a Java class has.
2. Enumerations can have Constructors, instance Variables, methods and can even
implementInterfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit [Link] class.
5. enum may implement many interfaces but cannot extend any class because it
internallyextends Enum class

JAVA ENUMERATIONS ARE CLASS TYPES


Enumeration with Constructor, instance variable and Method
 Java Enumerations Are Class Type.
 It is important to understand that each enum constant is an object of its
enumerationtype.
 When you define a constructor for an enum, the constructor is called when
eachenumeration constant is created.
 Also, each enumeration constant has its own copy of any instance variables
definedby the enumeration

Program 4: Example of Enumeration with Constructor, instance variable and


Method

Enum Days
{
Monday(),Tuesday();
String s;
Days()
{
S=”hai”;
}
void print()
{
[Link](s);
}
}
class Test
{
public static void main(String args[])
{

[Link]();
}
}

OUTPUT:
Hai

Example2

Enum Cars
{
Maruti(“baleno”),Tata(“nexon”);
String s;
Cars(String s)
{
this.s=s;
}
void print()
{
[Link](s);
}
}
class Test
{
public static void main(String args[])
{

[Link]();
}
}

OUTPUT:
Baleno

ENUMERATIONS INHERITS ENUM


 All enumerations automatically inherit one: [Link]. This class defines
several methods that are available for use by all enumerations.
 You can obtain a value that indicates an enumeration constant‘s position in the list of
constants. This is called its ordinal value, and it is retrieved by calling the ordinal( )
method.
 It has this general form: final int ordinal( )
 It returns the ordinal value of the invoking constant. Ordinal values begin at zero.
 Thus, in the Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel
hasan ordinal value of 1, RedDel has an ordinal value of 2, and so on.
 You can compare the ordinal value of two constants of the same enumeration by
usingthe compareTo( ) method.
 It has this general form: final int compareTo(enum-type e), Here, enum-type is the
type of the enumeration, and e is the constant being compared to the invoking
constant
 If the invoking constant has an ordinal value less than e‘s, then compareTo( ) returns
anegative value.
 If the two ordinal values are the same, then zero is returned.
 If the invoking constant has an ordinal value greater than e‘s, then a positive value is
returned.

Program : Example with ordinal(), comapareTo and equals() methods


enum Days
{
Monday,Tuesday;
}
public class Test{
public static void main(String[] args) {
Days d1=[Link];
Days d2=[Link];
[Link]([Link]());

if([Link](d2) < 0)
[Link](d1 + " comes before " + d2);
if([Link](d2) > 0)
[Link](d2+ " comes before " + d1);
if([Link](d2) == 0)
[Link](d1+ " equals " + d2);
if([Link](d2))
[Link](d1+ " equals " + d2);
if(d1== d3)
[Link](d1+ " == " + d2);
}
}
Output:
0
Monday comes before Tuesday
The Numeric Type Wrappers

 The most commonly used type wrappers are those that represent numeric values. These
are Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers
inherit the abstract class Number.
 Number declares methods that return the value of an object in each of the different
number formats. These methods are shown here:
1. byte byteValue( )
2. double doubleValue( )
3. float floatValue( )
4. int intValue( )
5. long longValue( )
6. short shortValue( )

doubleValue( ): returns the value of an object as a double


floatValue( ): returns the value as a float, and so on.
 All of the numeric type wrappers define constructors that allow an object to be
constructed from a given value, or a string representation of that value. For example, here
are the constructors defined for Integer:
Integer(int num) Integer(String str)
 If str does not contain a valid numeric value, then a NumberFormatException is
thrown. All of the type wrappers override toString( ). It returns the human-readable form
of the value contained within the wrapper. This allows you to output the value by passing
a type wrapper object to println( ), for example, without having to convert it into its
primitive type.

Program : All wrapper class


class Wrap {
public static void main(String args[]) {

Character c=new Character('@'); // character type


char c1=[Link]();
[Link]("Character wrapper class"+c1);

Boolean b=new Boolean(true);


boolean b1=[Link]();
[Link]("Boolean wrapper class"+b1);
Integer i1 = new Integer(100); // integre type
int i = [Link]();
[Link]("Integer wrapper class"+i); // displays 100 100

Float f1 = new Float(12.5); // Float type


float f = [Link]();
[Link]("Float wrapper class"+f);

output:

Character wrapper class@


Boolean wrapper classtrue
Integer wrapper class100
Float wrapper class12.5

Autoboxing

 Autoboxing is the process by which a primitive type is automatically encapsulated


(boxed) into its equivalent type wrapper whenever an object of that type is needed.
There is no need to explicitly construct an object.
 For example, converting int to Integer class. The Java compiler applies autoboxing
when a primitive value is:
 Passed as a parameter to a method that expects an object of the corresponding
wrapper class.
 Assigned to a variable of the corresponding wrapper class.
 Auto-unboxing is the process by which the value of a boxed object is automatically
extracted(unboxed) from a type wrapper when its value is needed. There is no need
to call a method such as intValue( ) or doubleValue( ).
 For example conversion of Integer to int. The Java compiler applies unboxing when an
object of a wrapper class is:
 Passed as a parameter to a method that expects a value of the corresponding
primitive type.
 Assigned to a variable of the corresponding primitive type.

Uses of Autoboxing and Unboxing


• Useful in removing the difficulty of manually boxing and unboxing
values in several algorithms.
• it is very important to generics, which operates only on objects.
• It also helps prevent errors.
• autoboxing makes working with the Collections Framework
• here is the modern way to construct an Integer object that
has the value 100:
Integer iOb = 100; // autobox an int
• Notice that no object is explicitly created through the use of new. Java handles
this for you,automatically.
• To unbox an object, simply assign that object reference to a primitive-type
variable.
• For example, to unbox iOb, you can use this line:
int i = iOb; // auto-unbox

Program: Simple program for autoboxing and autoUnboxing


class auto
{
public static void main(String[] args)
{
int a=10;
Integer k=a; //autoboxing
[Link](k);

}
}
output:
10

class auto
{
public static void main(String[] args)
{
Integer a=10;
int k=a; //unboxing
[Link](k);

}
}
output:
10

Autoboxing/Unboxing Occurs in Expressions:


 autoboxing and unboxing take place whenever a conversion into an object or from an
object is required.
 This applies to expressions. Within an expression, a numeric object is automatically
unboxed.
 The outcome of the expression is reboxed, if necessary

Program:
class auto {
public static void main(String args[]) {
int a=10,b=20;
Integer c=a+b;
[Link](c);
}
}

output:
30

Autoboxing/Unboxing Boolean and Character Values:


Java also supplies wrappers for boolean and char. These are Boolean and Character.
Autoboxing/unboxing applies to these wrappers, too
• Character ch = 'x'; // box a char
• char ch2 = ch; // unbox a char
• Boolean b = true; here the value true is boxed in b
• if(b) [Link]("b is true"); // here b is unboxed
Program:

class auto {
public static void main(String args[]) {
//Autobox/unbox a boolean.
Boolean b = true;
if(b)
[Link]("b is true");
// Autobox/unbox a char.
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
[Link]("ch2 is " + ch2);

}
}
output:
b is true
ch2 is x

Autoboxing/Unboxing Helps Prevent Errors:


 Autoboxing always creates the proper object and auto unboxing always produce the
proper value.
 There is no wayfor the process to produce the wrong type of object or value.
Program:
class auto {
public static void main(String args[]) {

Integer iOb = 1000; // autobox the value 1000


int i = [Link](); // manually unbox as byte !!!
[Link]("unbox value:"+i); // does not display 1000 !
}
}
output:
unbox value:-24
 This program displays not the expected value of 1000, but –24! The reason is that
the value inside iOb is manually unboxed by calling byteValue( ), which causes the
truncation of the value stored in iOb, which is 1,000.
 This results in the garbage value of –24 being assigned to i.
 Auto-unboxing prevents this type of error because the value in iOb will always
autounbox into a value compatible with int.

You might also like