Ilovepdf Merged
Ilovepdf Merged
W
جاهعة نيران
AJRAN UNIVERSITY
Distributed Information S
Course Code: 465CiS-3
Introduction
Creating a Thread
©
What is a Java Thread?
CPU
ع
سسا
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.
https: //www.jetbrains.com/
71/1/2021
م
a | EG] JetBrains: Developer Tox
Fy
< O 6 w jetbrains.com
dotMemory
dotPeek
dotTrace
PyCharm
Rider
RubyMine
WebStorm
Toolbox App
ed) EG intelli (DEA: The Java it > |+ v = 8 *
lutions Support
DOWNLOAD
م اق Intell) IDEA: The Java IC & [+ Vv - a
DEA
Capable and
مسد © 1421 م ع7نات#
Ultimate Community
For web and enterprise For JVM and Android
development development
Previous versions
Android ? v v
1
Edition Setup
||
6
ماعومه6
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 واس جم
net Security
ure Conmecton
Cancel
ef
ream]
fl
2
Ul
for cells
Lele
Setup
1
Edition Setup
cea
ae
ا
3
rea slo)
Setup
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
6
Continue
WE Customize Intell IDEA
Ul Themes
Set U! theme
© Darcula light
® 1: Project
import java
import j
7: Structure
JFrame frame = new JFrame ("Hello w
TLabel 1a = new
labe ont (new
Breakpounts iabel+ ij Sreakpoints
ame,
fr
frame
| + ع A
) @ Line Breakpoints
itive nformat
g Customize Intell’ IDEA
Ul Themes
Set U! theme
© Darcula
+ 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
Default plugins
Plugin Development
Plugin DevKit
Skip Remaining and Set Defaults Back to UI Therhes Next: Featured plugins
BE Customize Intell IDEA
- Featured plugins
Plugin for Scala fanguage support Emutates Vim editor Learn basic shortcuts and essential IDE
features with quick interactive exercises
Skip Remaining and Set Defaults Back to Default! plugins Start using Intell IDEA
IntelliJ IDEA
يمناimport Project
Ge Open
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
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.
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.")
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.
Thread
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.
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
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.
Now let's see how to use a Thread which begins with the main java thread that all Java
programs have.
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.
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:
1. New
2. Runnable
3. Running
4. Waiting
5. Dead/Stop
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 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();
}
}
** 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.
classMyThreadDemo
{
public static void main( String args[] )
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:
To create and start the above thread you can do like this:
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".
thread.start();
This example will print out the text "Thread running" once the run() method is executed
by the new thread.
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.
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".
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)
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:
Example:
And
To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:
Example:
And
Extending Java Thread
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.
}
}
Thread 2
package com.NU;
@Override
public void run() {
for (int i = 7; i >= 1 ; i--) {
System.out.println(i + " Thread 2");
}
}
}
Thread 3
package com.NU;
}
}
}
Thread 4
package com.NU;
@Override
public void run() {
}
}
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:
REVESION
How to create thread
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...
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.
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.
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.
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.
@Override
System.out.println(i);
try
catch (InterruptedException e)
e.printStackTrace();
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
package com.NU;
package com.NU;
@Override
public void run() {
try {
Thread.sleep(5000); ///this thread sleeps for 5 second
}
catch (InterruptedException e)
{e.printStackTrace();}
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:
Joining threads
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;
try{
Thread2.join();
}catch(Exception e){System.out.println(e);} /// Join method implementation
try{
Thread3.join();
}catch(Exception e){System.out.println(e);}
}
}
package com.NU;
@Override
public void run() {
for (int i = 1; i <= 9 ; i++)
{
System.out.println(i + " Thread 1");
}
}
}
package com.NU;
@Override
package com.NU;
}
}
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
Objective:
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 methods that are used to set the priority of thread shown as:
Method Description
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.
You can also set a thread's priority at any time after its creation using the setPriority method.
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.
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.
}
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:
More example:
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
More exercises
Exercise1: Execute the following program and write the output in the box below:
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
System.out.println("Thread B started");
for(int j=1;j<=4;j++)
}
System.out.println("Exit from B");
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
class ThreadPriority
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();
threadB.start();
threadC.start();
;Output:
Exercise2: Write a program in Java using Thread Priority concept and behavior where the
program with priority 10 will run first.
+ Thread.currentThread().getName());
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
Lab 7
Objective: Thread Synchronization
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:
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
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.
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
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.
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.
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
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.
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.
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.
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)
package com.NU;
t1.join();
t2.join();
System.out.println(c.balance);
}
}
package com.NU;
class bank {
int balance;
public void bankbalance()
{
balance++;
}
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!
package com.NU;
class bank {
int balance;
public synchronized void bankbalance()
{
balance++;
}