0% found this document useful (0 votes)
3 views35 pages

Unit 4 Threads and Packages

This document covers the concept of packages in Java, including built-in and user-defined packages, naming conventions, and how to create and use them. It also discusses access specifiers such as default, private, protected, and public, explaining their scopes and providing examples. Additionally, the document introduces threads as lightweight processes that execute concurrently within a program.

Uploaded by

udptl012
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)
3 views35 pages

Unit 4 Threads and Packages

This document covers the concept of packages in Java, including built-in and user-defined packages, naming conventions, and how to create and use them. It also discusses access specifiers such as default, private, protected, and public, explaining their scopes and providing examples. Additionally, the document introduces threads as lightweight processes that execute concurrently within a program.

Uploaded by

udptl012
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
You are on page 1/ 35

Unit – 4 Threads and Packages

4.1 Package
▪ A package is a group of similar types of classes, interfaces and sub-
packages.
▪ Package can be categorized into two forms:
1. Built-in Package
2. User-defined Package
▪ There are many built-in packages such as lang, awt, javax, swing,
net, io, util, sql, etc.
4.2 Package Naming conventions
▪ For avoiding unwanted package names, we have the following
naming conventions which we use in creating a package.
1. The package names starts with lower case letters and class name
begins with uppercase letter. They should be period-delimited.
e.g. java.awt.Color
Here, awt is packagename and Color is classname.
2. The names should be based on the company or organization
name.
▪ Package names follow the reverse order of domain names, that is,
org.techvidvan.tutorials.
▪ In order to define a package name based on an organization, we will
first reverse the company URL. After that, we define it by the
company and include division names and project names.
▪ For example, if we want to create a package out of
www.javatpoint.com , we will reverse it in the following way:
com.javatpoint
▪ If we want to define a sub-package of the com.javatpoint, we will
do it in the following way:
com.javatpoint.examples

1|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4.3 Types of package
▪ There are two types of packages:
1. Built-in package
2. User-defined package
1. Built-in package
▪ When we install java into a personal computer or laptop, many
packages get installed automatically. They all are unique on their
own and have the capabilities to handle multiple tasks.
▪ Some of the examples of built-in packages are listed below:
a) java.lang: It contains classes for primitive types, strings, math
functions, threads and exceptions.
b) java.util: It provides language utility classes such as the Scanner
class, Vector, dates, Calendars, etc.
c) java.io: It provide Input-Output support classes. For example,
data input string, data output string, file input string, etc.
d) java.awt: It provides classes for implementing Graphical User
Interface such as windows, buttons, menus, etc.
e) java.net: It provides classes for networking. Which is used to
communicate with other computers.
f) java.applet: It provides classes for creating and implementing
applets.

2|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
//importing java.lang package
import java.lang.*;
class Main
{
public static void main(String args[])
{
String a = "1230";
int b = Integer.parseInt(a);
System.out.println(b);
}
}
▪ In the above code, we are importing everything from java.lang
package. The function we can access due to this package is
parseInt().
▪ Due to this function, we can get integers from string variables.
▪ Variable 'a' of type string contains digits.
▪ To get this digits and store them into int type variable, we are
accessing the Integer class (defined inside java.lang package) and
using parseInt() to convert.
2. User-defined package
▪ User-defined packages are those that developers create to
incorporate different needs of applications.
▪ As the name suggests, these packages are defined by the user. We
create a directory whose name should be the same as the name of
the package. Then we create a class inside the directory.
▪ To create a package,
Step 1: we use the package keyword.
Syntax: package packagename;
Example: package pack1;
Step 2: Include class in java package, but remember that the class has
only one package declaration.

3|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
package pack1;
class gfg
{
public static void main(String args[])
{
…………function………..
}
}
Step 3: Now the user-defined package is successfully created, we can
import it into other packages and use its functions.
Example:
//A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//B.java
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

4|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4.4 How can we create sub package and import it into another
package?
✓ Package inside the package is known as subpackage. i.e. the package
that we are putting into another package is called "sub package".
✓ Let's take an example, Sun Microsystem has definded a package
named java that contains many classes like System, String, Reader,
Writer, Socket etc. These classes represent a particular group e.g.
Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang,
net, io etc. and put the Input/Output related classes in io package,
Server and ServerSocket classes in net packages and so on.
✓ The standard of defining package is domain.company.package e.g.
LearnJava.full.io.
✓ Example: In this example, we created a package LearnJava and a
sub package corejava in the Simple.java file.
Example:
package LearnJava.corejava;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello from subpackage");
}
}
✓ To compile the class, we can use the same command that we used
for package. The command is given below:
o javac -d . Simple.java
✓ To run the class stored into the created sub package, we can use the
below command:
o java LearnJava.corejava.Simple
✓ After successfully compiling and executing, it will print the
following output to the console.

5|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Output:
Hello from subpackage
4.5 How to use package in your program?
OR
What is package? Explain with example to create and use it in
another file.
Creating package:
✓ We can create a package by using the 'package' keyword. Choose a
name for the package and include a package command as the first
statement in the java source file. The java source file can contain the
classes, interfaces, enumerations and annotation types that you want
to include in the package.
✓ For example, the following statement creates a package named
MyPackage.
✓ This statement must be the first statement of the java file.
✓ Syntax: package MyPackage;
public class Classname
{
}
✓ We define a class with the Classname which is considered as a part
of the package name.
✓ It will be saved as "Classname.java" file which is located in a
directory named MyPackage.
✓ When the java file is compiled, java will create a (.) class file which
will be stored in the same directory.
✓ Java also supports the concept of package hierarchy, this can be
done by specifying multiple package names separated by (.)
operator.
✓ For example: maths.arithmetic.Add
Here, the package name maths will have a sub package arithmethic
which will have the Add class.

6|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Using packages:
✓ For using a package, we import the created package in our current
java file.
Example:
//A.java in p1 package
package p1;
public class A
{
public void display()
{
System.out.println("Hello");
}
}
//Test.java
import p1.A;
class Bnew
{
public void displayB()
{
System.out.println("Hello B");
}
}
public class Test
{
public static void main(String args[])
{
A obj = new A();
obj.display(); //display called from class A
Bnew obj1=new Bnew();
obj1.displayB(); //display called from class Bnew
}
}
✓ In above example, we are using the display method from the
package p1 and displayB method from the class Bnew.

7|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
✓ For running this program, A.java and Test.java do the following:
//Move to package p1
o cd p1
//compile A.java which is in package p1
o javac A.java
//To move out from package p1
o cd..
//To compile Test.java
o javac -d . Test.java
//To run Test.java
o java Test
4.6 Access Specifiers through package
▪ Access modifiers help to restrict the scope of a class, constructor,
variable, method or data member.
▪ There are four types of access modifiers available in Java:
1. Default
2. Private
3. Protected
4. public
1. default:
▪ When no access modifier is specified for a class, method or
data member, it is said to be having the default access
modifier by default.
▪ The default access modifier are accessible only within the
same package.

Example:
package pack;
class Default
{
void display()

8|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
{
System.out.println("Hello World!");
}
}
******************************************************
import pack.Default;
// This class is having default access modifier
class DefaultMod
{
public static void main(String args[])
{
// Accessing class Default from package pack
Default obj = new Default();
obj.display();
}
}
➢ Here, the scope of class Default and its method display is default
so it cannot be accessed from outside the package.
2. private:
▪ It is specified using the private keyword.
▪ When variables and methods are declared private, they cannot
be accessed outside of the class.
▪ Classes or Interfaces can not be declared as private.

Example:
class DataNew
{
// private variable
private String name;
}
public class Data
{
public static void main(String[] args)
{
// create an object of Data

9|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
DataNew d = new DataNew();
// access private variable and field from another class
d.name = "Programiz";
System.out.println(d.name);
}
}
➢ Here, we have declared a private variable named name.
➢ When we run the program, we will get the following error:
Data.java:30: error: name has private access in DataNew
d.name = "Programiz";
Data.java:31: error: name has private access in DataNew
System.out.println(d.name);
➢ The error is generated because we are trying to access the private
variable of the DataNew class from the Data class.
➢ If we need to access the private variables, we can use the getters
and setters method.

Example:
package pack;
public class PrivateData
{
private String name;

// getter method
public String getName()
{
return this.name;
}
// setter method
public void setName(String name)
{
this.name= name;
}
}

10 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
******************************************************
import pack.PrivateData;
public class PrivateGet
{
public static void main(String[] args)
{
PrivateData d = new PrivateData();

// access the private variable using the getter and setter


d.setName("Programiz");
System.out.println(d.getName());
}
}
➢ Here, we have a private variable named name. To access the
variable from the outer class, we have used getName() and
setName() methods. These methods are called getter and setter.
➢ Here, we have used setter method setName() to assign value to
the variable and the getter method getName() to access the
variable.
➢ We have used this keyword inside the setName() to refer to the
variable of the class.
3. Protected:
▪ It is specified using the protected keyword.
▪ The protected access modifier is accessible within the same
package and outside the package but through inheritance only.
▪ The protected access modifier can be applied on the data
members, methods and constructor.
▪ We cannot declare classes or interfaces protected in java.
Example:
package pack;
public class Animal
{
// protected method
protected void display()

11 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
{
System.out.println("Different types of Animals are there");
}
}
******************************************************
import pack.Animal;
class Dog extends Animal
{
public static void main(String[] args)
{
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
➢ We have protected method named display() inside the Animal
class.
➢ The Animal class is inherited by the Dog class. Then, we have
created dog object of Dog class. We tried to access the protected
method of the parent class using object.
➢ Since protected methods can be accessed from the child classes,
we are able to access the method of Animal class from the Dog
class.
4. public:
▪ This modifier is specified using the public keyword.
▪ When methods, variables, classes are declared public, then we
can access them from anywhere.
▪ The public access modifier has no scope restriction.
Example:
package pack;
public class Public
{
// public variable
public int legCount;
12 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
// public method
public void display()
{
System.out.println(" Animals are in the jungle.");
System.out.println("They have " + legCount + " legs.");
}
}
******************************************************
import pack.Public;
public class PublicMain
{
public static void main(String[] args)
{
// accessing the public class
Public p = new Public();

// accessing the public variable


p.legCount = 4;
// accessing the public method
p.display();
}
}
➢ Here, the public variable legCount is accessed from the
PublicMain class.
➢ The public method display() is accessed from the PublicMain
class.

13 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4.7 Introduction to Threads
▪ Threads are small lightweight processes.
▪ It is a sequence of steps executed at the same time.
▪ Thread is similar to a program that has a single flow of execution.
▪ It has a beginning, body, and end and executes sequentially.
▪ Every program has at least one thread.

Example:
class Data
{
start;
body;
end;
}
4.8 Multithreading
▪ Modern operating system has the capability to execute several
programs simultaneously i.e. at the same time. This ability is known
as multitasking.
▪ Multithreading is a conceptual programming paradigm where a
program is divided into two or more subprograms which can be
implemented at the same time in parallel.
▪ A program that contains multiple flow of control is known as
multithreaded programming.
▪ The ability to support multithreads is referred to as concurrency.
▪ A thread is similar to a program that has a single flow of control. It
has a beginning, a body and an end. All the program which we have
done till now are called as single threaded program as they have
single flow of execution.
▪ Java has a unique property that it supports multithreading. That is,
Java enables us to use multiple flow of control in developing
program and each flow of control is considered as a separate
program known as thread.

14 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Difference between Multithreading and Multitasking
Multithreading Multitasking
It is a programming concept. It is an operating system concept.
It supports execution of multiple It supports execution of multiple
parts of the same programs tasks simultaneously.
simultaneously.
The processor switches between The processor switches between
different parts or threads of the multiple tasks or processes.
program.
It is highly efficient. It is less efficient as compared to
multithreading.
It helps in developing efficient It helps in developing efficient
programs. OS.

Creating Threads
▪ For creating thread in java we create it in the form of objects that
contain run() method. The run() method is the heart and soul of
any thread. It makes the entire body of the thread. A run() looks
like:
public void run()
{
……………..
……………..
}
▪ The run() method is invoked by calling the start() method. now
remember this that if you want this run() method to behave like
Threaded program, you need to call the start() method. If you will
call it by its name viz. run(), it is not going to show any
multithreading property.
▪ There are two ways to create a thread:
1. By creating a Thread class: For this you need to extend
“Thread” class.
2. By converting a class to thread: For this you need to implement
the “Runnable” interface.

15 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
1. By extending Thread class:
o In order to create a threaded program, we have to extend the
java.lang.Thread class. This given the access to all the thread
methods directly. The steps are:
1. Declare the class as extending the Thread class.
2. Implement the run() method.
3. Create a thread object and call the start() methods.
o We use the following constructors for creating the Thread:
▪ Thread
▪ Thread(Runnable r)
▪ Thread(String name)
▪ Thread(Runnable r, String name)

Example:
//extends the Thread class
public class Test extends Thread
{
//override the run() method
public void run()
{
//Thread task
System.out.println("Thread task");
}
public static void main(String args[])
{
//create an object of test class
Test t = new Test();
//invoking Thread
t.start(); //start method will create a callstack for Thread
//t.start(); //Throws an Exception
}
}

16 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. By implementing Runnable interface
o The Runnable interface declares the run() method that is
required for implementing threads in our programs.
o Perform the following steps:
1. Declare the class as implementing the Runnable interface.
2. Implement the run() method.
3. Create a thread by defining an object that is instantiated
from this “runnable” class as the target of the thread.
4. Call the thread’s start() method to run the thread.
Example:
//Implements the Runnable Interface
class X implements Runnable //step 1
{
public void run() //step 2
{
for(int i=1; i<=10; i++)
{
System.out.println("\t Thread X" +i);
}
System.out.println("End of Thread X");
}
}
class RunnableTest
{
public static void main(String args[])
{
X runnable = new X();
Thread threadx = new Thread(runnable); //step 3
threadx.start(); //step 4
System.out.println("End of main Thread");
}
}
➢ In the main method, we first create an instance of X and then
pass this instance as the initial value of the object threadX(an
object of Thread class).

17 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
➢ Whenever, the new thread threadX starts up, its run() method
calls the run() method of the target object supplied to it.
➢ Here, the target object is runnable.
4.9 Thread Methods
▪ The Thread class defines several methods that helps to manage
threads.
Method Meaning
getName It returns the name of the thread
setName It changes the name of the thread
isAlive It determines if a thread is still running
Join Wait for a thread to terminate
Run Entry point for the thread
Start Start a thread by calling its run method
Sleep Suspend a thread for a period of time
Yield It causes current thread on halt and other threads
to execute
getPriority It returns the priority of the thread
setPriority It changes the priority of the thread

a) Naming Methods
▪ The naming methods are:
o getName() : To get name of current thread.
o setName(String name) : To set the name of thread.
Example:
class GetName extends Thread
{
public void run()
{
//System.out.println(Thread.currentThread().getName());
System.out.println("Thread task is printed by: " +
Thread.currentThread().getName());
}
public static void main(String args[])
{

18 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
System.out.println("Hello is printed by: " +
Thread.currentThread().getName());
GetName g1 = new GetName(); // create object of GetName
class
g1.setName("Smruti");
g1.start(); // one more thread created By default the name of
this thread is Thread o.

GetName g2 = new GetName();


g2.setName("Programming");
g2.start();//one more thread created its name is Thread-1.
}
}

Example:
class GetName extends Thread
{
public static void main(String args[])
{
System.out.println("Hello");
//get name of current thread
System.out.println(Thread.currentThread().getName());
//set the name of currentthread
Thread.currentThread().setName("Smruti");
System.out.println(Thread.currentThread().getName());
System.out.println(10/0); //Exception in main thread
}
}
b) Join method
▪ If a thread wants to wait for another thread to complete its task
then we should use join() method.
▪ Syntax:
1) public final void join() throws InterruptedException
2) public final synchronized void join(long ms) throws
InterruptedException
19 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
//Main method will wait until JoinMethod complete its task.
class JoinMethod extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("child thread: " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
public static void main(String args[]) throws InterruptedException
//because join() throws interruptedexception
{
//create object of main Thread
JoinMethod j = new JoinMethod();
j.start();
j.join(); //By using this first child thread will run and then main
thread will run
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main thread: " + i);
Thread.sleep(1000);
}
}
20 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
catch(InterruptedException e)
{
}
}
}

Example:
//JoinMethodNew will wait until main method complete its task.
class JoinMethodNew extends Thread
{
//instance variable of mainthread
//main method is static so static instance passed
static Thread mainthread;
public void run()
{
try
{
mainthread.join();
for(int i=1;i<=5;i++)
{
System.out.println("child thread: " + i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
//because join() throws interruptedexception
public static void main(String args[]) throws InterruptedException
{
//create reference of main Thread
mainthread = Thread.currentThread();
JoinMethodNew j = new JoinMethodNew();
j.start();
try
21 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
{
for(int i=1;i<=5;i++)
{
System.out.println("Main thread: " + i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
c) Yield() method
▪ Which stops the current executing thread and gives the chance
to other threads for execution.
▪ Working:
o In Java 5: Internally it uses sleep().
o In Java 6: Thread provides the hint to the thread
scheduler. Then it depends on thread scheduler to accept
or ignore the hint. If it accepts then current thread stops
its execution and give a chance to other thread. If it
ignores then current thread continues its execution.
▪ Method: public static native void yield();
▪ Output may be different each time we run the program.
Example:
public class YieldMethod extends Thread
{
public void run()
{
//Thread.yield();
for(int i=1; i<=5; i++)
{

22 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
System.out.println(Thread.currentThread().getName() + " -
"+i);
}
}
public static void main(String args[])
{
YieldMethod y = new YieldMethod();
y.start();
// if you want main method to stop and provide chance to other
threads for execution.
Thread.yield();
for(int i=1; i<=5; i++)
{
System.out.println(Thread.currentThread().getName() + " -
"+i);
}
}
}
d) isAlive()
▪ The isAlive() method of thread class tests if the thread is alive. A
thread is considered alive when the start() method of thread class
has been called and the thread is not yet dead.
▪ This method returns true if the thread is still running and not
finished.
▪ Syntax: public final boolean isAlive()
▪ Return: This method will return true if the thread is alive
otherwise returns false.
Example:
public class IsAliveExp extends Thread
{
public void run()
{
try

23 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
{
Thread.sleep(300);
System.out.println("is run() method isAlive
"+Thread.currentThread().isAlive());
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
IsAliveExp t1 = new IsAliveExp();
System.out.println("before starting thread isAlive:
"+t1.isAlive());
t1.start();
System.out.println("after starting thread isAlive:
"+t1.isAlive());
}
}
e) Suspend()
▪ The suspend() method of thread class puts the thread from
running to waiting state. This method is used if you want to stop
the thread execution and start it again when a certain event
occurs.
▪ This method allows a thread to temporarily stop the execution.
▪ The suspended thread can be resumed using the resume() method.
▪ Syntax: public final void suspend()
▪ Return: This method does not return any value.

24 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4.10 Thread Model
o The Java thread model can be defined in the following categories:
1. Thread priorities
2. Synchronization
1. Thread priorities
❖ In Java, every thread is assigned a priority and based on this
priority the threads are executed.
❖ Usually all the threads have equal priority and therefore, they
share the processor on a first-come, first-serve basis.
❖ Java allows us to set the priority of a thread using the
setPriority() method as follows:
ThreadName.setPriority(intNumber)
Here, intNumber is an integer value to which the thread’s
priority is set. The Thread class provides us many thread
priority constants:
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
❖ Here, the intNumber may be set to any priority level from 1 to
10. 1 denoting least priority, 10 denoting highest priority. If
we apply above or below this range then it will throw an
IllegalArgumentException.
❖ Default Priority: The default priority only for main thread is
5 but for all remaining threads default priority will be inherited
from parent to child(Thread).

25 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
public class ThreadPriority extends Thread
{
public void run()
{
System.out.println("Child Thread");
System.out.println("child thread priority" +
Thread.currentThread().getPriority());
}
public static void main(String args[])
{
System.out.println("Main Thread old priority" +
Thread.currentThread().getPriority());
//changing main thread priority
Thread.currentThread().setPriority(10);
System.out.println("Main Thread new priority" +
Thread.currentThread().getPriority());
//using thread priority constants
Thread.currentThread().setPriority(NORM_PRIORITY);
System.out.println("Main Thread new priority" +
Thread.currentThread().getPriority());
ThreadPriority t = new ThreadPriority();
t.setPriority(4);//prints 4 in child thread
t.start();
}

26 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Synchronization
❖ We know that threads use their own data and methods
provided inside their run() method. Consider a case when they
try to use data and methods outside themselves. In such
situation they may compete for the same resource and may
lead to serious problems.
❖ For an instance, suppose there are two threads, one thread may
be reading the data from the resource and the second thread
may be writing data at the same time. In such situation, result
will be unexpected. Java enables us to overcome this situation
using a technique called Synchronization.
❖ The keyword synchronized helps to solve such problems by
keeping a watch on such locations. For example, the method
that will read information from a file and the method that will
update the same file may be declared as synchronized.
❖ Example:
synchronized void update()
{
………………
……………… //code here is synchronized
………………
}
synchronized void read()
{
………………
……………… //code here is synchronized
………………
}
❖ When we declare a method as synchronized, Java creates a
"monitor" and hands it over to the thread that calls the method
first time. As long as the thread holds the monitor, no other
thread can enter the synchronized section of code.

27 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
❖ It is also possible to make a block of code as synchronized:
synchronized (lock-object)
{
…………..;
…………..;
}
Example:
class BookTheaterSeat
{
int total_seats=10;
synchronized void bookSeat(int seats)
{
if(total_seats >= seats)
{
System.out.println(seats + " seats booked
successfully");
total_seats = total_seats-seats;
System.out.println("seats left" + total_seats);
}
else
{
System.out.println("Sorry seats cannot be
booked");
System.out.println("Seats left:" + total_seats);
}
}
}
public class MovieBookApp extends Thread
{
static BookTheaterSeat b;
int seats;
synchronized public void run()
{
b.bookSeat(seats);

28 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
}
public static void main(String args[])
{
b = new BookTheaterSeat();
MovieBookApp m1 = new MovieBookApp();
m1.seats=7;
m1.start();

MovieBookApp m2 = new MovieBookApp();


m2.seats=6;
m2.start();
}
}
Deadlock
✓ Deadlock in java is a part of multithreading.
✓ Deadlock can occur in a situation 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.
✓ Deadlock describes a situation where two or more threads are
blocked forever, waiting for each other. Deadlock occurs when
multiple threads need the same locks but obtain them in different
order.
✓ A Java multithreaded program may suffer from the deadlock
condition because the synchronized keyword causes the execution
thread to block while waiting for the lock, or monitor, associated
with the specified object. Here is an example

29 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4.11 Inter-Thread communication
❖ Inter-thread communication is a mechanism in which a thread
releases the lock and enter into paused state and another thread
acquires the lock and continue to executed.
❖ Java implements inter-thread communication with the help of
following three methods:
1. wait():
▪ sends the calling thread into the sleep mode.
▪ This thread can now be activated only by notify() or notifyall()
methods.
▪ One can also specify the time for which the thread has to wait.
▪ The desired waiting time period is specified as an argument to
the wait method.
▪ Syntax:
public final void wait() throws InterruptedException (waits
until object is notified)
2. notify(): This method is used to wake up a single thread and
releases the object lock.
Syntax: public final void notify()
3. notifyall(): This method is used to wake up all threads that are in
waiting state.
Syntax: public final void notifyAll()
Note: To call wait(), notify() or notifyAll() method on any object,
thread should own the lock of that object i.e. the thread should be
inside synchronized area.
▪ Since all the methods declared as final, they cannot be
overridden.
▪ All the three methods throw InterruptedException

30 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class TotalEarnings extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
for(int i=1;i<=10;i++)
{
total=total+100; // 1 ticket price is 100
}
this.notify();
}
}
}
public class InterThread
{
public static void main(String args[]) throws InterruptedException
{
TotalEarnings te = new TotalEarnings();
te.start();
//System.out.println("Total Earnings:" +te.total+"Rs.");
synchronized(te)
{
te.wait();
System.out.println("Total Earnings:" +te.total+" Rs.");
}
}
}

31 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4.12 Lifecycle of Threads
▪ During the life time of a thread, there are many states it can enter.
They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
▪ A thread is always in one of these five states. It can move from one
state to another via a variety of ways as shown in the following
figure:

32 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
1. Newborn state:
o When a thread object is created, the thread is said to be in born
state.
o At this moment, the thread is not scheduled for running. At
this state, we can do only one of the following things with it:
▪ We can run the thread by calling start() method.
▪ We can kill the thread by using stop() method.

o If scheduled, it moves to the runnable state. If we attempt to


use any other method at this stage, an exception will be
thrown.
2. Runnable state:
o The Runnable state means that the thread is ready for
execution and is waiting for the availability of the processor.
o In simple terms, the thread is ready but has not got the
processor time.

33 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
o All the thread has equal priority and hence all follow a queue
system and the processor gives time to each thread in round
robin fashion, i.e., first-come, first-serve manner.
3. Running state:
o Running means that the processor has given its time to the
thread for its execution. A running thread may have following
conditions:
a) It has been suspended using suspend() method. A
suspended thread is revived by using resume() method.

b) It has been made to sleep using sleep(time) method where


time is in milliseconds. After the given time the thread
itself joins the Runnable state.

c) It has been told to wait until some event occurs. This is


done using wait() method and it scheduled to run again by
notify() method.

34 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4. Blocked state:
o A thread is said to be blocked when it is prevented from
entering into the runnable state and the running state. This
happens when the thread is suspended, sleeping or waiting in
order to satisfy certain requirements.
5. Dead state:
o A thread is said to be in dead state when it has been killed
using stop() method or it has successfully completed its
execution.
Difference between wait() and sleep()
No. wait() sleep()
1 wait() method releases the sleep() method doesn't release the
lock. lock.
2 It is the method of Object It is the method of Thread class.
class.
3 It is the non-static method. It is the static method.
4 Should be notified by notify() After the specified amount of
or notifyAll() methods. time, sleep is completed.

35 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT

You might also like