0% found this document useful (0 votes)
59 views95 pages

Ilovepdf Merged

Uploaded by

RaNä Karam
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)
59 views95 pages

Ilovepdf Merged

Uploaded by

RaNä Karam
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/ 95

hk

W
‎‫جاهعة نيران‬
AJRAN UNIVERSITY

College of Computer Science and Information Systems


Department of Information System
Sem 3 (Summer Semester) 2020/2021

Distributed Information S
Course Code: 465CiS-3

Dr. Mohamed Elmagzoub Abdalla


[email protected]
2
NG
‫جامعة نجران‬
NAJRAN UNIVERSITY
2

Introduction

What is a Java Thread?

—> Thread Lifecycle

Creating a Thread

©
What is a Java Thread?

Thread is a lightweight sub process

It is the smallest independent unit of a program

Contains a separate path of execution

Every Java program contains at least one thread

A thread is created & controlled by the java.lang.Thread class


Process ID : 50

Thread 1 Thread 2 Thread 1 | Thread 2 [tesa |

CPU

‫ع‬
‫سسا‬

Java Thread Life-Cycle

eS
Thread Lifecycle

A new thread begins its life cycle in this state & remains here until the program
starts the thread. It is also known as a born thread.
1
-

Once a newly born thread starts, the thread comes under runnable state. A thread
stays in this state is until itis executing its task.
0

Runnable
|
:

In this state a thread starts executing by entering run() method and the yield()
method can send them to go back to the Runnable state.
x
i

\
\

A thread enters this state when it is temporarily in an inactive state i.e it is still
q 63

alive but is not eligible to run. It is can be in waiting, sleeping or blocked state.
Terminated
|

Terminated

A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

edureka! JAVA CERTIFICATION TRAINING www.edureka.co/java-j2ee-soa-training


fi
Creating a Thread
Creating A Thread
A thread in Java can be created using two ways

Thread Class Runnable Interface

public class Thread


extends Object public interface Runnable
implements Runnable
Download From here:

https: //www.jetbrains.com/

71/1/2021
‫م‬
a | EG] JetBrains: Developer Tox
Fy
< O 6 w jetbrains.com

Tools angus Support

AppCode ReSharper TeamCity PyCharm Edu

CLion Rider Upsource IntelliJ IDEA Edu


Find a tool for Datalore ReSharper C++ YouTrack JB Academy
you
DataGrip dotCover Hub

dotMemory

dotPeek
dotTrace
PyCharm

Rider
RubyMine

WebStorm

Toolbox App
ed) EG intelli (DEA: The Java it > |+ v = 8 *

Www jetbrains.com Sg ‎‫ع‬ 7 2


a © 10

lutions Support

IntelliJ IDEA Coming in 2019.2. What'sNew Features Learn Buy Download

Upcoming V Thursday, May 30, 2019, 14:00-15:00 GMT X

DOWNLOAD
‫م‬ ‫اق‬ Intell) IDEA: The Java IC & [+ Vv - a‫‏‬

€ 4 2 6 www jetbrains.com tx 3 LZ.

IntelliJ IDEA Coming in 2019.2. What'sNew Features Learn Buy Download

Upcoming Webinar: Thursday, May 30, 2019, 14:00-15:00 GMT XX

DEA
Capable and
‫مسد‬ © 1421‫ م ع‬7‫نات‬#

‫ذم مع كاه اطاع ز ديدم لاا‬ ‫دهن‬ ‫مك‬ ‫لذهل‬


Download Intell) IDEA:

oO 0 17 ‎‫ق تناع ز باو‬5 1+ ‫ص‬ t ‎‫جاه‬ ‫عب‬ ‫يم‬ wf

52 Intellid IDEA Coming in 2019.2 What'sNew Features Learn Buy Download

Ultimate Community
For web and enterprise For JVM and Android
development development

AL EXE | DOWNLOAD EXE

Free trial Free, open-source


System requirements
installation Instructions

Previous versions

License Commercial Open-source, Apache 2.0

Java, Kotlin, Groovy, v ‎.‫ي‬


Scala

Android ? v v

Maven, Gradie, SBT v ‎‫ا‬ ‫يه‬


Thank you for downloar

€ © i ww jetbrains.com > eg ‎‫ع‬ 1 ©

IntelliJ IDEA Coming in 2019.2. What'sNew Features Learn Buy Download

Thank you for downloading IntelliJ


IDEA!
Your download should start shortly. If it doesn't, please use the direct
link.
Download and verify the file SHA-256 checksum

Third-party software used by IntelliJ IDEA Community Edition

at nd. * a‫‏‬ 7 ~~ ‫ع‬ 58 ‫وي‬ ‫عزو‬ ‫و‬ ‫هسرييرو‬


‫جب‬‫ع‬

What do you want to do with idealC-2019.1.2.exe (478 MB)? 2


From: download-cf jetbrains.com ‎‫رجاس‬ ‫د‬ =
‫كنا‬
‫لاخ‬
‫ةك‬ ‫ل‬

Welcome to IntelliJ IDEA

1
Edition Setup

||

6
‫ ماعومه‬6

Choose install Location


the h if it wheck

ity Edition i the follo


ides

pace required.
Space available

Cancel
‫كان‬ ‫لك‬

Setup
Installation Options
gure your Intell

vanable

launchers &
Options
ure your Intell

vanable

Cancel
Berea Cel)

Installation Options
Configure your intelli

TH variable

inchers dir te
IDEA‫‏‬ ‫واس جم‬

you would like t


Jer

net Security
ure Conmecton

Cancel
ef
ream]

fl
2
Ul
for cells
Lele
Setup

| Completing IntelliJ IDEA Community

1
Edition Setup
cea
ae

‫ا‬
3
rea slo)

Setup

Completing IntelliJ IDEA Community

1
Edition Setup

‫أ ع‬
‫ زاأاءنما‬01‫شع‬
ee‫‏‬

]|

a
PPro
‫زا‬ at

|
2
lle ferce lis
Edge

1
‫ن‬1 ‫ل‬a)‫‏‬
‫ت‬
Tas
‫بن‬ ‫ل‬

2
‫لاننا‬
Edge‫‏‬

lin

3
Tce ay

‫ل‬4
eas

import settings
‫بن‬
Data Col)

pt these

1
2‫أ‬
‫لديل‬ JetBrains Privacy Policy
ae‫‏‬
Version 2.0, last updated: May 18th, 2018
scribe the type »
2 and our a

i
me
f time of the ourchas

read and accept the terms of this User Agr

6
Continue
WE Customize Intell IDEA

Ul Themes

Set U! theme

© Darcula light

module ‎‫باوابعه‬ module src (@& HelloWorld


*” HelloWerld java

® 1: Project
import java
import j

public class HelioW


public &

7: Structure
JFrame frame = new JFrame ("Hello w
TLabel 1a = new
labe ont (new
Breakpounts iabel+ ij Sreakpoints
ame,
fr
frame
| + ‎‫ع‬ A

) @ Line Breakpoints

( & Java Exception Breakpoints


O
public sté

Skip Remaining and Set Defaults


Recycle Bin

Q

eae ducts by sending 7 aout f


guration, stat ypes of files, numbe

itive nformat
g Customize Intell’ IDEA

Ul Themes

Set U! theme

© Darcula

module stc @ Hetioworld


F HelloWorld java

+ MF 1: Project
import
import 3

public class
25 public HelloWorl
5 JFrame frame = new JFrame ("Bello w
2
A TLabel labe new mii:
label.setFont (new Font ("Serif", Font
Breakpounts tabel+ Ej sreakpoints

+ ‎‫اعد‬ a
} @ Line Breakpoints
5
][ & Java Exception Breakpoints
O14

Skip Remaining and Set Defaults Next: Default plugins


Customize intelli IDEA

Default plugins

Tune IDEA to your tasks

Build Tools Version Controls Test Tools


Ant, Maven, Gradle Git, GitHub, Mercurial, Subversion JUnit, TestNG-J, Coverage

Android Other Tools


UI Designer Android Bytecode Viewer, Eclipse, Jove Stream
Debugger.

Plugin Development
Plugin DevKit

Skip Remaining and Set Defaults Back to UI Therhes Next: Featured plugins
BE Customize Intell IDEA

- Featured plugins

Download featured plugins

IdeaVim IDE Features Trainer

Plugin for Scala fanguage support Emutates Vim editor Learn basic shortcuts and essential IDE
features with quick interactive exercises

Recommended only if you are


familiar with Vin,

Install Install and Enadle install

Skip Remaining and Set Defaults Back to Default! plugins Start using Intell IDEA
IntelliJ IDEA

+ Create New Project

‎‫ يمنا‬import Project

Ge Open

L? Check out from Version Control ¥

x Configure * Get Help ¥


BACHELOR OF SCIENCE IN INFORMATION SYSTEMS
LAB 1
Thread and Multithread
465CIS-3
DISTRIBUTED SYSTEMS

Objective:
The objective of this lab is to
1) To understand that concept of threads in java
2) To create and use threads in java
3) To demonstrate multithreading

What hardware and software do we need?


We need a computer with an Intel 386, Intel 486, or one of the Pentium processors. Our
operating system may be some version of Microsoft Windows, MS-DOS, or even Linux
running a DOS emulator. The following are either required or recommended:

Before editing, compiling and running the program in JCreator (JCreator is the
development tool for every programmer that likes to do what he does best: programming.
It is faster, more efficient and more reliable than other Java IDE’s (Integrated Development
Environment). Therefore it is the perfect tool for programmers of every level, from learning
programmer to Java-specialist), we must have Java (JDK-Java Development Kit) in our
computer.

Downloading and Installation of Java and IDE software:


Downloading JDK and Docs
Step1: To download JDK, go to
http://java.sun.com/javase/downloads/index.jsp
Find JDK 6 Update 14 (or the latest available) and click Download. In the pop-down
menu, select Windows platform, and check “I agree to the Java SE Development Kit 6u14
License Agreement” and click Continue. Check the “Java SE Development Kit 6u14” and
click on the name of the file jdk-6u14-windows-i586.exe. Click Save in the dialog box
that pops up and save the JDK file (about 73 MB) to the desktop or a folder of your choice.
Step2: Now download the documentation. To do that, return to the download page
http://java.sun.com/javase/downloads/index.jsp

LAB 1-2, Instructor: Dr. Magzoub Page 1


Scroll down to Java SE Documentation and click Download. Choose Documentation and
English from the pull-down lists, click Continue, and download the zipped documentation
file (about 56 MB) to the desktop or a folder of your choice.
Installing JDK and Docs
Important Note: Install the JDK and documentation first, then an IDE.
Step3: To install the JDK, run the downloaded JDK file, for example
jdk-6u14-windows-i586.exe
and follow the instructions. Accept all the defaults. By default, the JDK is installed in the
appropriate C:\Program Files\Java\jdk-... folder.
Step4: Now install the documentation. This may take up to one hour. Open the zipped
documentation folder, for example
jdk-6u10-docs.zip
and copy its docs subfolder into the folder where JDK is installed.
Documentation can be accessed by opening the index.html file from the docs folder in a
browser; it is also used for context-sensitive JDK help in IDEs.
Step4: Downloading and Installing JCreator
To download JCreator, go to
http://www.jcreator.com/download.htm
Choose the second link --
JCreator LE v5.0
Click on the Download button and download the JCreator setup file jcrea500_setup.exe
(about 6 MB) to the desktop or a folder of your choice.
Step5: To install JCreator, run jcrea500_setup.exe. Accept all the defaults.
Step6: Running a Java Program in JCreator
Start JCreator
From the File menu choose New --> File, click on Java Classes, click on Empty Java File,
click next.
Type in the name of your file, for example, HelloWorld. Capitalization is important! Then
click Finish. Browse to a folder where you want to save your file, for example, C:\mywork.

Step7: or downloading and launching Eclipse from http://www.eclipse.org/downloads/


Step8: Running a Java Program in Eclipse following the steps as mentioned bellow:

1. Start Eclipse.
2. Create a new Java Project:
1. File->New->Project.
2. Select "Java" in the category list.
3. Select "Java Project" in the project list. Click "Next".
4. Enter a project name into the Project name field, for example, "Hello
World Project".
5. Click "Finish"--It will ask you if you want the Java perspective to open.
(You do.)
3. Create a new Java class:
1. Click the "Create a Java Class" button in the toolbar. (This is the icon
below "Run" and "Window" with a tooltip that says "New Java Class.")

LAB 1-2, Instructor: Dr. Magzoub Page 2


2. Enter "HelloWorld" into the Name field.
3. Click the checkbox indicating that you would like Eclipse to create a
"public static void main(String[] args)" method.
4. Click "Finish".
4. A Java editor for HelloWorld.java will open. In the main method enter the
following line.
System.out.println("Hello World");
5. Save using ctrl-s. This automatically compiles HelloWorld.java.
6. Click the "Run" button in the toolbar (looks like a little man running).
7. You will be prompted to create a Launch configuration. Select "Java
Application" and click "New".

Click "Run" to run the Hello World program. The console will open and display "Hello
World".

Reading:

You should read the following topics before starting any exercise on thread and
multithread:

1. Thread class
2. Runnable interface
3. Thread lifecycle
4. Thread methods

Ready Reference

Introduction
Nearly every operating system supports the concept of processes -- independently running
programs that are isolated from each other to some degree. Threading is a facility to allow
multiple activities to coexist within a single process. Java is the first mainstream
programming language to explicitly include threading within the language itself.
A process can support multiple threads, which appear to execute simultaneously and
asynchronously to each other. Multiple threads within a process share the same memory
address space, which means they have access to the same variables and objects, and they
allocate objects from the same heap.

Process and Thread are two basic units of execution. Concurrency programming is more
concerned with java threads.

LAB 1-2, Instructor: Dr. Magzoub Page 3


Process

A process is a self contained execution environment and it can be seen as a program or


application. However a program itself contains multiple processes inside it. Java runtime
environment runs as a single process which contains different classes and programs as
processes.

Thread

LAB 1-2, Instructor: Dr. Magzoub Page 4


Thread can be called lightweight process. Thread requires less resources to create and
exists in the process, thread shares the process resources.

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:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

The Thread class defines several methods that help manage threads. The table below
displays the same:

Method Meaning

getName() It returns the name of the thread.

Obtain thread’s name

getPriority Obtain thread’s priority

setPriority(int setPriority(int newpriority)


newpriority)

Run() Entry point for the thread

Sleep(int This method makes the thread sleep hence the thread's
milliseconds) execution will pause for milliseconds provided and after
that, again the thread starts executing. This help in
synchronization of the threads.

Suspend a thread for a period of time

LAB 1-2, Instructor: Dr. Magzoub Page 5


start() This method starts the execution of the thread and JVM calls
the run() method on the thread.

Start a thread by calling its run method

Now let's see how to use a Thread which begins with the main java thread that all Java
programs have.

Every Java program uses threads:

Every Java program has at least one thread -- the main thread. When a Java program starts,
the JVM creates the main thread and calls the program's main() method within that thread.
The JVM also creates other threads that are mostly invisible to you – for example, threads
associated with garbage collection, object finalization, and other JVM housekeeping tasks.
Other facilities create threads too, such as the AWT or Swing UI toolkits, servlet
containers, application servers, and RMI (Remote Method Invocation).

A thread is the smallest unit of processing that can be performed in an OS. In most
modern operating systems, a thread exists within a process - that is, a single process may
contain multiple threads.

A Web browser is an example of a multithreaded application. Within a typical browser,


you can scroll a page while it’s downloading an applet or an image, play animation and
sound concurrently, print a page in the background while you download a new page, or
watch three sorting algorithms race to the finish.

LAB 1-2, Instructor: Dr. Magzoub Page 6


Some texts call a thread a lightweight process. A thread is similar to a real process in that
both have a single sequential flow of control. However, a thread is considered lightweight
because it runs within the context of a full-blown program and takes advantage of the
resources allocated for that program and the program’s environment.

Thread Lifecycle:

The lifecycle of thread consist of several states which thread can be in. Each thread is in
one state at any given point of time.
1. New State: - Thread object was just created. It is in this state before the start () method
is invoked. At this point the thread is considered not alive.
2. Runnable or ready state:- A thread starts its life from Runnable state. It enters this state
the time start() is called but it can enter this state several times later. In this state, a thread
is ready to run as soon as it gets CPU time.
3. Running State:- In this state, a thread is assigned a processor and is running. The thread
enters this state only after it is in the Runnable state and the scheduler assigns a processor
to the thread.
4. Sleeping state: - When the sleep method is invoked on a running thread, it enters the
Sleeping state.
5. Waiting State:- A thread enters the waiting state when the wait method is invoked on
the thread. When some other thread issues a notify () or notifyAll (), it returns to the
Runnable state().
6. Blocked State: - A thread can enter this state because it is waiting for resources that are
held by another thread – typically I/O resources.
7. Dead State:- This is the last state of a thread. When the thread has completed execution
that is its run () method ends, the thread is terminated. Once terminated, a thread can’t be
resumed.
8. The life cycle is as follows:

Or:

LAB 1-2, Instructor: Dr. Magzoub Page 7


There are various stages of life cycle of thread as shown in above diagram:

1. New
2. Runnable
3. Running
4. Waiting
5. Dead/Stop

LAB 1-2, Instructor: Dr. Magzoub Page 8


1. New: In this phase, the thread is created using class "Thread class". It remains in
this state till the program starts the thread. It is also known as born thread.
2. Runnable: In this page, the instance of the thread is invoked with a start method.
The thread control is given to scheduler to finish the execution. It depends on the
scheduler, whether to run the thread.
3. Running: When the thread starts executing, then the state is changed to "running"
state. The scheduler selects one thread from the thread pool, and it starts
executing in the application.
4. Waiting: This is the state when a thread has to wait. As there multiple threads are
running in the application, there is a need for synchronization between threads.
Hence, one thread has to wait, till the other thread gets executed. Therefore, this
state is referred as waiting state.
5. Dead: This is the state when the thread is terminated. The thread is in running
state and as soon as it completed processing it is in "dead state".

LAB 1-2, Instructor: Dr. Magzoub Page 9


Creating a thread
Java defines two ways by which a thread can be created.

 By implementing the Runnable interface.


 By extending the Thread class (Inheritance).

Implementing the Runnable Interface


The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement
the run() method, which is of form,
public void run()

 run() method introduces a concurrent thread into your program. This thread will end
when run() method terminates.
 You must specify the code that your thread will execute inside run() method.
 run() method can call other methods, can use other classes and declare variables just
like any other normal method.

class MyThread implements Runnable


{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
LAB 1-2, Instructor: Dr. Magzoub Page 10
Thread t = new Thread(mt);
t.start();
}
}

concurrent thread started running..


To call the run() method, start() method is used. On calling start(), a new stack is
provided to the thread and run() method is called to introduce the new thread into the
program.
Note: If you are implementing Runnable interface in your class, then you need to
explicitly create a Thread class object and need to pass the Runnable interface
implemented class object as a parameter in its constructor.

** If you are not extending the Thread class, your class object would not be treated as a
thread object. So you need to explicitly create Thread class object. We are passing the
object of your class that implements Runnable so that your class run() method may execute.

Extending Thread class


This is another way to create a thread by a new class that extends Thread class and
create an instance of that class. The extending class must override run() method which is
the entry point of new thread.
class MyThread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

classMyThreadDemo
{
public static void main( String args[] )

LAB 1-2, Instructor: Dr. Magzoub Page 11


{
MyThread mt = new MyThread();
mt.start();
}
}

concurrent thread started running..


In this case also, we must override the run() and then use the start() method to run the
thread. Also, when you create MyThread class object, Thread class constructor will also
be invoked, as it is the super class, hence MyThread class object acts as Thread class
object.

What if we call run() method directly without using start() method ?


In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.run();
}
Doing so, the thread won't be allocated a new call stack, and it will start running in the
current call stack, that is the call stack of the main thread. Hence Multithreading won't be
there.

LAB 1-2, Instructor: Dr. Magzoub Page 12


Can we Start a thread twice ?
No, a thread cannot be started twice. If you try to do
so, IllegalThreadStateException will be thrown.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
mt.start(); //Exception thrown
}
When a thread is in running state, and you try to start it again, or any method try to
invoke that thread again using start() method, exception is thrown.

Again,

Thread Subclass

The first way to specify what code a thread is to run, is to create a subclass of Thread and
override the run() method. The run() method is what is executed by the thread after you
call start(). Here is an example of creating a Java Thread subclass:

public class MyThread extends Thread {

public void run(){


System.out.println("MyThread running");
}
}

To create and start the above thread you can do like this:

MyThread myThread = new MyThread();


myTread.start();

The start() call will return as soon as the thread is started. It will not wait until
the run() method is done. The run() method will execute as if executed by a different
CPU. When the run() method executes it will print out the text "MyThread running".

You can also create an anonymous subclass of Thread like this:

LAB 1-2, Instructor: Dr. Magzoub Page 13


Thread thread = new Thread(){
public void run(){
System.out.println("Thread Running");
}
}

thread.start();

This example will print out the text "Thread running" once the run() method is executed
by the new thread.

Runnable Interface Implementation

The second way to specify what code a thread should run is by creating a class that
implements java.lang.Runnable. The Runnable object can be executed by a Thread.

Here is a Java Runnable example:

public class MyRunnable implements Runnable {

public void run(){


System.out.println("MyRunnable running");
}
}

To have the run() method executed by a thread, pass an instance of MyRunnable to


a Thread in its constructor. Here is how that is done:

Thread thread = new Thread(new MyRunnable());


thread.start();

When the thread is started it will call the run() method of the MyRunnable instance
instead of executing it's own run() method. The above example would print out the text
"MyRunnable running".

You can also create an anonymous implementation of Runnable, like this:

Runnable myRunnable = new Runnable(){

public void run(){


System.out.println("Runnable running");
}
}
LAB 1-2, Instructor: Dr. Magzoub Page 14
Thread thread = new Thread(myRunnable);
thread.start();

Subclass or Runnable?

There are no rules about which of the two methods that is the best. Both methods works.
Personally though, I prefer implementing Runnable, and handing an instance of the
implementation to a Threadinstance. When having the Runnable's executed by a thread
pool it is easy to queue up the Runnableinstances until a thread from the pool is idle. This
is a little harder to do with Thread subclasses.

Sometimes you may have to implement Runnable as well as subclass Thread. For
instance, if creating a subclass of Thread that can execute more than one Runnable. This
is typically the case when implementing a thread pool.

Again,

Thread Creation
There are two ways to create thread in java;
1. Implement the Runnable interface (java.lang.Runnable) (Create a class that
implements the Runnable interface)
2. By Extending the Thread class (java.lang.Thread) (Create a class that extends the
Thread class)

1. Implementing the Runnable Interface


One way to create a thread in java is to implement the Runnable Interface and then
instantiate an object of the class. We need to override the run() method into our class which
is the only method that needs to be implemented. The run() method contains the logic of
the thread.

The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the
Thread constructor. The Thread object now has a Runnable object that implements the
run() method.
3. The start() method is invoked on the Thread object created in the previous step. The
start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing
an uncaught exception.

Example:
1st method: Threads by implementing Runnable interface
Create a class that implements the interface Runnable and override run() method:

LAB 1-2, Instructor: Dr. Magzoub Page 15


class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
Creating Object:
MyThread myObject = new MyThread();
Creating Thread Object:
Thread thr1 = new Thread( myObject );
Start Execution:
thr1.start();

Example:

class MyThread implements Runnable {


public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// I can call start(), and this will call run().
t.start();
} // end main()
} // end class ThreadEx2

And

To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:

public void run( )


Inside run( ), we will define the code that constitutes the new thread. Example:

public class MyClass implements Runnable {


public void run(){
System.out.println("MyClass running");
}
}
To execute the run() method by a thread, pass an instance of MyClass to a Thread in its
constructor (A constructor in Java is a block of code similar to a method that's called
when an instance of an object is created). Here is how that is done:

LAB 1-2, Instructor: Dr. Magzoub Page 16


Thread t1 = new Thread(new MyClass ());
t1.start();
When the thread is started it will call the run() method of the MyClass instance instead of
executing its own run() method. The above example would print out the text "MyClass
running ".

2. Extending java.lang.Thread class


A class can also extend the Thread class to create a thread. When we extend the Thread
class, we should override the run method to specify the thread action.

2nd method: Extending Thread class


Create a class by extending Thread class and override run() method:

class MyThread extends Thread


{
public void run() // override rum method
{
// thread body of execution
}
}
Create a thread:
MyThread thr1 = new MyThread();
Start Execution of threads:
thr1.start();
Create and Execute:
new MyThread().start();

Example:

class MyThread extends Thread { // the thread


public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx1 { // a program that utilizes the thread
public static void main(String [] args ) {
MyThread t = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
t.start();
} // end main()
} // end class ThreadEx1

And
Extending Java Thread

LAB 1-2, Instructor: Dr. Magzoub Page 17


The second way to create a thread is to create a new class that extends Thread, then
override the run() method and then to create an instance of that class. The run() method is
what is executed by the thread after you call start(). Here is an example of creating a Java
Thread subclass:

public class MyClass extends Thread {


public void run(){
System.out.println("MyClass running");
}
}
To create and start the above thread you can do so like this:

MyClass t1 = new MyClass ();


t1.start();
When the run() method executes it will print out the text " MyClass running ".

So far, we have been using only two threads: the main thread and one child thread.
However, our program can affect as many threads as it needs. Let's see how we can create
multiple threads.

LAB 1-2, Instructor: Dr. Magzoub Page 18


Multithreading:

Running 4 threads at the same time (A Program with four Threads)

Main Thread (Thread 1)


package com.NU;

public class Main {

public static void main(String[] args) {


for (int i = 1; i <= 10 ; i++) {
System.out.println(i + " Thread 1");
}

Thread Thread2 = new Thread2();


Thread2.start();

Thread Thread3 = new Thread(new Thread3());


Thread3.start();

Thread Thread4 = new Thread4();


Thread4.start();

}
}

Thread 2
package com.NU;

public class Thread2 extends Thread {

@Override
public void run() {
for (int i = 7; i >= 1 ; i--) {
System.out.println(i + " Thread 2");
}
}
}
Thread 3
package com.NU;

public class Thread3 implements Runnable {


@Override
public void run() {
for (int i = 7; i >= 1 ; i--) {
System.out.println(i + " Thread 3");

}
}
}

Thread 4
package com.NU;

public class Thread4 extends Thread {

@Override
public void run() {

for (int i = 7; i >= 1 ; i--) {


System.out.println(i + " Thread 4");
}

}
}
Output
1 Thread 1
2 Thread 1
3 Thread 1
4 Thread 1
5 Thread 1
6 Thread 1
7 Thread 1
8 Thread 1
9 Thread 1
10 Thread 1
7 Thread 2
6 Thread 2
5 Thread 2
4 Thread 2
3 Thread 2
2 Thread 2
1 Thread 2
7 Thread 4
6 Thread 4
5 Thread 4
7 Thread 3
4 Thread 4
3 Thread 4
6 Thread 3
2 Thread 4
5 Thread 3
1 Thread 4
4 Thread 3
3 Thread 3
2 Thread 3
1 Thread 3
BACHELOR OF SCIENCE IN COMPUTER SCIENCE

Lab 4
Sleep Method in Thread/ Multithread
456CSS-3
PARALLEL AND DISTRIBUTED SYSTEMS

Objective:

The objective of this lab is to

1) To understand sleep method in thread


2) To demonstrate sleep method in thread

REVESION
How to create thread

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.
3.
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:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
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.

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().
1. public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:thread is running...

2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}

Output:thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitely create Thread class object. We are passing the object of your
class that implements Runnable so that your class run() method may execute.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java


The Thread class provides two methods for sleeping a thread:
o public static void sleep(long miliseconds)throws InterruptedException
o public static void sleep(long miliseconds, int nanos)throws InterruptedException

Parameters
millis − This is the length of time to sleep in milliseconds.

Return Value
This method does not return any value.

Exception
InterruptedException − if any thread has interrupted the current thread. The interrupted status of
the current thread is cleared when this exception is thrown.

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being
executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.

The try and catch keywords come in pairs.

Note:

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a
method of Java’s throwable class which prints the throwable along with other details like the
line number and class name where the exception occurred.

printStackTrace() is very useful in diagnosing exceptions. For example, if one out of five
methods in your code cause an exception, printStackTrace() will pinpoint the exact line in
which the method raised the exception.
The following example shows how to use Thread.sleep() method.

class MyThread extends Thread

@Override

public void run()

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

System.out.println(i);

try

sleep(1000); //this thread sleeps for 1 second

catch (InterruptedException e)

e.printStackTrace();

public class ThreadsInJava


{

public static void main(String[] args)

MyThread thread = new MyThread();

thread.start();

Note:

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a
method of Java’s throwable class which prints the throwable along with other details like the
line number and class name where the exception occurred.

printStackTrace() is very useful in diagnosing exceptions. For example, if one out of five
methods in your code cause an exception, printStackTrace() will pinpoint the exact line in
which the method raised the exception.

Example 2

To make Thread1 execute before Thread2:

package com.NU;

public class Main {

public static void main(String[] args) {

Thread Thread1 = new Thread1();


Thread1.start(); /// calling Thread1

Thread Thread2 = new Thread2();


Thread2.start(); /// calling Thread2
}
}
package com.NU;

public class Thread1 extends Thread {


@Override
public void run() {
for (int i = 1; i <= 10 ; i++) {
System.out.println(i + "Thread1");
}
}
}

package com.NU;

public class Thread2 extends Thread {

@Override
public void run() {
try {
Thread.sleep(5000); ///this thread sleeps for 5 second
}
catch (InterruptedException e)
{e.printStackTrace();}

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


System.out.println(i + "Thread2");
}
}
}
Output without Sleep Method: Output with Sleep Method:
1 Thread 2 1 Thread 1

2 Thread 2 2 Thread 1

3 Thread 2 3 Thread 1

4 Thread 2 4 Thread 1

1 Thread 1 5 Thread 1

5 Thread 2 6 Thread 1

6 Thread 2 7 Thread 1

7 Thread 2 8 Thread 1

8 Thread 2 9 Thread 1

9 Thread 2 1 Thread 2

2 Thread 1 2 Thread 2

3 Thread 1 3 Thread 2

4 Thread 1 4 Thread 2

5 Thread 1 5 Thread 2

6 Thread 1 6 Thread 2

7 Thread 1 7 Thread 2

8 Thread 1 8 Thread 2

9 Thread 1 9 Thread 2
BACHELOR OF SCIENCE IN COMPUTER SCIENCE

Lab 5
Join Method in Thread/ Multithread
456CSS-3
PARALLEL AND DISTRIBUTED SYSTEMS

Objective:

The objective of this lab is to

1) To demonstrate join method in thread

Joining threads

Sometimes one thread needs to know when other thread is terminating. In


java, isAlive() and join()are two different methods that are used to check whether a thread has
finished its execution or not.

But, join() method is used more commonly than isAlive(). This method waits until the thread on
which it is called terminates.
Using join() method, we tell our thread to wait until the specified 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.

As we have seen in the Introduction to Multithreading, the main thread must always be the last
thread to finish its execution. Therefore, we can use Thread join() method to ensure that all the
threads created by the program has been terminated before the execution of the main thread.
Example of thread without join() method

You want the execution to be in this order: Thread 2, Thread 3 finally Thread 1
package com.NU;

public class Main {

public static void main(String[] args) {

Thread Thread2 = new Thread2();


Thread2.start();

try{
Thread2.join();
}catch(Exception e){System.out.println(e);} /// Join method implementation

Thread Thread3 = new Thread3();


Thread3.start();

try{
Thread3.join();
}catch(Exception e){System.out.println(e);}

Thread Thread1 = new Thread1();


Thread1.start();

}
}

package com.NU;

public class Thread1 extends Thread {

@Override
public void run() {
for (int i = 1; i <= 9 ; i++)
{
System.out.println(i + " Thread 1");
}

}
}
package com.NU;

public class Thread2 extends Thread {

@Override

public void run() {

for (int i = 1; i <= 9 ; i++)

System.out.println(i + " Thread 2");


}

package com.NU;

public class Thread3 extends Thread {


@Override
public void run() {

for (int i = 1; i <= 9 ; i++)

System.out.println(i + " Thread 3");


}

}
}
Output:
1 Thread 2
2 Thread 2
3 Thread 2
4 Thread 2
5 Thread 2
6 Thread 2
7 Thread 2
8 Thread 2
9 Thread 2
1 Thread 3
2 Thread 3
3 Thread 3
4 Thread 3
5 Thread 3
6 Thread 3
7 Thread 3
8 Thread 3
9 Thread 3
1 Thread 1
2 Thread 1
3 Thread 1
4 Thread 1
5 Thread 1
6 Thread 1
7 Thread 1
8 Thread 1
9 Thread 1

Output without the Join Method:


1 Thread 2
2 Thread 2
1 Thread 1
2 Thread 1
1 Thread 3
3 Thread 1
3 Thread 2
4 Thread 2
5 Thread 2
6 Thread 2
7 Thread 2
8 Thread 2
9 Thread 2
4 Thread 1
5 Thread 1
2 Thread 3
6 Thread 1
3 Thread 3
4 Thread 3
5 Thread 3
7 Thread 1
8 Thread 1
9 Thread 1
6 Thread 3
7 Thread 3
8 Thread 3
9 Thread 3
BACHELOR OF SCIENCE IN INFORMATION SYSTEMS
Lab 6
Thread Scheduling and Priority

Objective:

The objective of this lab is to

1) To demonstrate thread priorities and scheduling

What hardware and software do we need?

We need a computer with an Intel 386, Intel 486, or one of the Pentium processors. Our
operating system may be some version of Microsoft Windows, MS-DOS, or even Linux running
a DOS emulator. The following are either required or recommended:

Before editing, compiling and running the program in JCreator (JCreator is the development tool
for every programmer that likes to do what he does best: programming. It is faster, more efficient
and more reliable than other Java IDE’s (Integrated Development Environment). Therefore it is
the perfect tool for programmers of every level, from learning programmer to Java-specialist),
we must have Java (JDK-Java Development Kit) in our computer.

Reading:

You should read the following topics before starting this exercise:
1. Thread priorities and scheduling, including

Ready Reference

In Java, thread scheduler can use the thread priorities in the form of integer value to each of its
thread to determine the execution schedule of threads. Thread gets the ready-to-run state
according to their priorities. The thread scheduler provides the CPU time to thread of highest
priority during ready-to-run state.
Priorities are integer values from 1 (lowest priority given by the constant
Thread.MIN_PRIORITY) to 10 (highest priority given by the constant
Thread.MAX_PRIORITY). The default priority is 5(Thread.NORM_PRIORITY).

Constant Description

The minimum priority of any thread


Thread.MIN_PRIORITY
(an int value of 1)

The maximum priority of any thread


Thread.MAX_PRIORITY
(an int value of 10)

The normal priority of any thread (an


Thread.NORM_PRIORITY
int value of 5)

The methods that are used to set the priority of thread shown as:

Method Description

This is method is used to set the priority


setPriority()
of thread.

This method is used to get the priority of


getPriority()
thread.
When a Java thread is created, it inherits its priority from the thread that created it. At any given
time, when multiple threads are ready to be executed, the runtime system chooses the runnable
thread with the highest priority for execution. In Java runtime system, preemptive scheduling
algorithm is applied. If at the execution time a thread with a higher priority and all other threads
are runnable then the runtime system chooses the new higher priority thread for execution. On
the other hand, if two threads of the same priority are waiting to be executed by the CPU then
the round-robin algorithm is applied in which the scheduler chooses one of them to run
according to their round of time-slice.

Thread Scheduler

In the implementation of threading scheduler usually applies one of the two following strategies:

 Preemptive scheduling? If the new thread has a higher priority then current running
thread leaves the runnable state and higher priority thread enter to the runnable state.

 Time-Sliced (Round-Robin) Scheduling? A running thread is allowed to be executing


for the fixed time, after completion the time, current thread indicates to another thread to
enter it in the runnable state.

You can also set a thread's priority at any time after its creation using the setPriority method.

Thread scheduler has the following properties:

Determines which runnable threads to run


Can be based on thread priority
Part of OS or Java Virtual Machine (JVM)
Many computers can run multiple threads simultaneously (or nearly so)

Summary, from an abstract or a logical perspective, multiple threads execute as concurrent


sequences of instructions. This may be physically true for multiprocessor systems, under certain
conditions. However, in the general case, multiple threads do not always physically execute at
the same time. Instead, the threads share execution time with each other based on the availability
of the system's CPU (or CPUs).

The approach used to determining which threads should execute at a given time is referred to as
scheduling. Scheduling is performed by the Java runtime system. It schedules threads based on
their priority. The highest-priority thread that is in the runnable state is the thread that is run at
any given instant. The highest-priority thread continues to run until it enters the death state,
enters the not runnable state, or has its priority lowered, or when a higher-priority thread
becomes runnable.

A thread's priority is an integer value between MIN_PRIORITY and MAX_PRIORITY. These


constants are defined in the Thread class. In Java 1.0, MIN_PRIORITY is 1 and
MAX_PRIORITY is 10. A thread's priority is set when it is created. It is set to the same priority
as the thread that created it. The default priority of a thread is NORM_PRIORITY and is equal to
5. The priority of a thread can be changed using the setPriority() method.

Priority of a Thread (Thread Priority):

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 it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread{


public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}

Output:

running thread name is:Thread-0

running thread priority is:10

running thread name is:Thread-1

running thread priority is:1

More example:

class A extends Thread


{
public void run()
{
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}}
class B extends Thread
{
public void run()
{
System.out.println("Thread B started");
for(int j=1;j<=4;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}}
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();

threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);

System.out.println("Started Thread A");


threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();

System.out.println("End of main thread");


}}

More exercises
Exercise1: Execute the following program and write the output in the box below:

class A extends Thread

public void run()

System.out.println("Thread A started");

for(int i=1;i<=4;i++)

System.out.println("\t From ThreadA: i= "+i);

System.out.println("Exit from A");

class B extends Thread

public void run()

System.out.println("Thread B started");

for(int j=1;j<=4;j++)

System.out.println("\t From ThreadB: j= "+j);

}
System.out.println("Exit from B");

class C extends Thread

public void run()

System.out.println("Thread C started");

for(int k=1;k<=4;k++)

System.out.println("\t From ThreadC: k= "+k);

System.out.println("Exit from C");

class ThreadPriority

public static void main(String args[])

A threadA=new A();

B threadB=new B();

C threadC=new C();

threadC.setPriority(Thread.MAX_PRIORITY);

threadB.setPriority(threadA.getPriority()+1);

threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");

threadA.start();

System.out.println("Started Thread B");

threadB.start();

System.out.println("Started Thread C");

threadC.start();

System.out.println("End of main thread");

;Output:
Exercise2: Write a program in Java using Thread Priority concept and behavior where the
program with priority 10 will run first.

Write your Code here:

class priority implements Runnable {

public void run() { for (int x = 1; x <= 3; x++)

System.out.println(x + " This is thread "

+ Thread.currentThread().getName());

public static void main(String[] args)

Thread t1 = new Thread(new priority(), "Thread A");

Thread t2 = new Thread(new priority(), "Thread B");

Thread t3 = new Thread(new priority(), "Thread C");

t3.setPriority(10);

t1.start();

t2.start();

t3.start();

}
Output:
Najran University
College of Computer Science and Information Systems
Department of Information System
Sem 3 (Summer Semester) 2020/2021

Distributed Information Systems


Course Code: 465CIS-3

Lab 7
Objective: Thread Synchronization

The objective of this lab is to


1) To demonstrate multithreading
2) To demonstrate synchronized thread

What hardware and software do we need?


We need a computer with an Intel 386, Intel 486, or one of the Pentium processors. Our
operating system may be some version of Microsoft Windows, MS-DOS, or even Linux
running a DOS emulator. The following are either required or recommended:

Before editing, compiling and running the program in JCreator (JCreator is the
development tool for every programmer that likes to do what he does best: programming.
It is faster, more efficient and more reliable than other Java IDE’s (Integrated
Development Environment). Therefore it is the perfect tool for programmers of every
level, from learning programmer to Java-specialist), we must have Java (JDK-Java
Development Kit) in our computer.

Reading:
You should read the following topics before starting this exercise:
1. Thread class
2. Thread methods
3. Thread synchronization

Ready Reference

In Java, the threads are executed independently to each other. These types of threads are called as
asynchronous threads. But there are two problems may be occur with asynchronous threads.

 Two or more threads share the same resource (variable or method) while only one of
them can access the resource at one time.
 If the producer and the consumer are sharing the same kind of data in a program then
either producer may produce the data faster or consumer may retrieve an order of data
and process it without its existing.

Suppose, we have created two methods as increment( ) and decrement( ). which increases or
decreases value of the variable "count" by 1 respectively shown as:

public void increment( ) {


count++;
}

public void decrement( ) {


count--;
}

public int value() {


return count;
}

When the two threads are executed to access these methods (one for increment( ),another for
decrement( )) then both will share the variable "count". In that case, we can't be sure that what
value will be returned of variable "count". We can see this problem in the diagram shown below:

To avoid this problem, Java uses monitor also known as ?semaphore? to prevent data from
being corrupted by multiple threads by a keyword synchronized to synchronize them and
intercommunicate to each other. It is basically a mechanism which allows two or more threads to
share all the available resources in a sequential manner. Java's synchronized is used to ensure that
only one thread is in a critical region. Critical region is a lock area where only one thread is run
(or lock) at a time. Once the thread is in its critical section, no other thread can enter to that
critical region. In that case, another thread will has to wait until the current thread leaves its
critical section.
General form of the synchronized statement is as:

synchronized(object) {

// statements to be
synchronized

Lock:

Lock term refers to the access granted to a particular thread that can access the shared resources.
At any given time, only one thread can hold the lock and thereby have access to the shared
resource. Every object in Java has build-in lock that only comes in action when the object has
synchronized method code. By associating a shared resource with a Java object and its lock, the
object can act as a guard, ensuring synchronized access to the resource. Only one thread at a time
can access the shared resource guarded by the object lock.

Since there is one lock per object, if one thread has acquired the lock, no other thread can acquire
the lock until the lock is not released by first thread. Acquire the lock means the thread currently
in synchronized method and released the lock means exits the synchronized method.
Remember the following points related to lock and synchronization:

 Only methods (or blocks) can be synchronized, Classes and variable cannot be
synchronized.
 Each object has just one lock.
 All methods in a class need not to be synchronized. A class can have both synchronized
and non-synchronized methods.
 If two threads wants to execute a synchronized method in a class and both threads are
using the same instance of the class to invoke the method then only one thread can
execute the method at a time.

 If a class has both synchronized and non-synchronized methods, multiple threads can still
access the class's non-synchronized methods. If you have methods that don't access the
data you're trying to protect, then you don't need to synchronize them. Synchronization
can cause a hit in some cases (or even deadlock if used incorrectly), so you should be
careful not to overuse it.
 If a thread goes to sleep, it holds any locks it has?it doesn't release them.
 A thread can acquire more than one lock. For example, a thread can enter a synchronized
method, thus acquiring a lock, and then immediately invoke a synchronized method on a
different object, thus acquiring that lock as well. As the stack unwinds, locks are released
again.
 You can synchronize a block of code rather than a method.
 Constructors cannot be synchronized

There are two ways to synchronize the execution of code:

1. Synchronized Methods
2. Synchronized Blocks (Statements)

Synchronized Methods:

Any method is specified with the keyword synchronized is only executed by one thread at a
time. If any thread want to execute the synchronized method, firstly it has to obtain the objects
lock. If the lock is already held by another thread, then calling thread has to wait.
Synchronized methods are useful in those situations where methods are executed concurrently, so
that these can be intercommunicate manipulate the state of an object in ways that can corrupt the
state if . Stack implementations usually define the two operations push and pop of elements as
synchronized, that?s why pushing and popping are mutually exclusive operations. For Example if
several threads were sharing a stack, if one thread is popping the element on the stack then
another thread would not be able to pushing the element on the stack.

Synchronized Blocks (Statements)

Another way of handling synchronization is Synchronized Blocks (Statements). Synchronized


statements must specify the object that provides the native lock. The synchronized block allows
execution of arbitrary code to be synchronized on the lock of an arbitrary object.

General form of synchronized block is:

synchronized (object reference


expression)
{
// statements to be synchronized
}

Threads need to share access to objects and may update shared objects
 For example multiple threads may access a database for an online
flight booking system

 We can synchronise threads so that they must complete their action before
another thread is scheduled
 We do this by tagging methods as synchronized
 When a synchronised method is being executed, the object is
locked and no other method can access the object until the
method completes

Example – An online seat reservation system


• Seats for a concert can be reserved through booking agents
• The processing for each booking agent runs in a separate thread – possibly
on a different processor
• Each booking transaction must check seat availability before reserving the
seat
Synchronization

At times when more than one thread try to access a shared resource, we need to ensure
that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. The synchronization keyword in java creates a block
of code referred to as critical section.

General Syntax :

synchronized (object)

//statement to be synchronized

Every Java object with a critical section of code gets a lock associated with the object. To
enter critical section a thread need to obtain the corresponding object's lock.

Why we use Syncronization ?

If we do not use syncronization, and let two or more threads access a shared resource at
the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts
execution and save certain values in a file temporary.txt which will be used to calculate
some result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the
values saved by T1 in the file temporary.txt (temporary.txt is the shared resource). Now
obviously T1 will return wrong result.

To prevent such problems, synchronization was introduced. With synchronization in


above case, once T1 starts using temporary.txt file, this file will be locked(LOCK mode),
and no other thread will be able to access or modify it until T1 returns.

Using Synchronized Methods

Using Synchronized methods is a way to accomplish synchronization. But lets first see
what happens when we do not use synchronization in our program.

In the above program, object fnew of class First is shared by all the three running
threads(ss, ss1 and ss2) to call the shared method(void display). Hence the result is
unsynchronized and such situation is called Race condition.

Synchronized Keyword

To synchronize above program, we must synchronize access to the


shared display() method, making it available to only one thread at a time. This is done by
using keyword synchronized with display() method.

synchronized void display (String msg)

Using Synchronized block

If you have to synchronize access to an object of a class or you only want a part of a
method to be synchronized to an object then you can use synchronized block for it.

Difference between synchronized keyword and synchronized block

When we use synchronized keyword with a method, it acquires a lock in the object for
the whole method. It means that no other thread can use any synchronized method until
the current thread, which has invoked it's synchronized method, has finished its
execution.
synchronized block acquires a lock in the object only between parentheses after the
synchronized keyword. This means that no other thread can acquire a lock on the locked
object until the synchronized block exits. But other threads can access the rest of the code
of the method.

Which is more preferred - Synchronized method or Synchronized block?

In Java, synchronized keyword causes a performance cost. A synchronized method in


Java is very slow and can degrade performance. So we must use synchronization
keyword in java when it is necessary else, we should use Java synchronized block that is
used for synchronizing critical section only.

Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any
shared resource.

Java Synchronization is better option where we want to allow only one thread to access
the shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

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 in java)

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the


example:

package com.NU;

public class Main {

public static void main(String[] args) throws Exception {

bank c = new bank();

Thread t1 = new Thread(new Runnable() {


public void run() {
for (int i = 1; i <= 2000 ; i++)
{
c.bankbalance();
}
}
});

Thread t2 = new Thread(new Runnable() {


public void run() {
for (int i = 1; i <= 2000 ; i++)
{
c.bankbalance();
}
}
});
t1.start();
t2.start();

t1.join();
t2.join();

System.out.println(c.balance);

}
}

package com.NU;

class bank {
int balance;
public void bankbalance()
{
balance++;
}

Output without Synchronization:

2876

If Thread 1 (t1) adds 2000 and Thread 2 (t2) adds, the Output should be 4000.
The problem is: the two Threads are reading from the memory at the same time!

Now we will change the bank class to be synchronized

package com.NU;

class bank {
int balance;
public synchronized void bankbalance()
{
balance++;
}

Output with Synchronization:


4000
Because of synchronized block this program gives the expected output.

You might also like