SlideShare a Scribd company logo
1 of 64
Multi-threaded
programming
Chapter-02-unit 3
contents
▪ Multithreaded fundamentals
▪ The thread class and runnable interface
▪ Creating a thread
▪ Creating multiple threads
▪ Determining when a thread ends
▪ Thread priorities
▪ Synchronization
▪ Using synchronized methods
▪ The synchronized statement
▪ Thread communication using notify(), wait() and notifyall()
▪ Suspending , resuming and stopping threads
Introduction
▪ A multithreaded program contains two or more
parts that can run concurrently.
▪ Each part of such a program is called thread
▪ Each thread defines a separate path of execution.
▪ Multithreading is a specialized form of
multitasking.
Multithreading fundamentals
▪ There are two distinct types of multitasking:
– Process based
– Thread based
▪ A process is a program that is executing
▪ Process –based multitasking is the feature that
allows you to run two or more programs
concurrently.
▪ Eg.: running Java compiler and editing text in text
editor simultaneously.
▪ In thread based multitasking environment, thread
is the smallest unit of dispatchable code.
▪ Means a single program can perform two or more
tasks at once.
▪ Eg.. Text editor can be formatting text at the same
time that is printing.
Advantages of multithreading
▪ It enables you to write very efficient programs
because it lets you utilize the idle time is present in
most programs.
▪ I/O devices such as keyboard, disk drives etc are
slower than CPU. Thus program will spend
maximum of time in waiting to send or receive
information to or from the device.
▪ By using multithreading , your program can
execute the another task during the idle time
▪ Eg. When one part of the program is sending a file
over the internet, another part can be reading
keyboard input, still another can be buffering the
next block of data to send.
▪ A thread can be in several states
– It can be running.
– It can be ready to run as soon it gets CPU time.
– A running thread can be suspended, which is temporary
halt for execution.
– It can be resumed later.
– A thread can be blocked when waiting for a resource.
– A thread can be terminated, in which case its execution
ends and cannot be resumed.
▪ Synchronization: it allows the execution of threads
to be coordinated in a certain well defined ways.
The thread class and runnable
interface
▪ Java’s multithreading system is built upon the
Thread class and its companion interface ,
Runnable.
▪ Both are packaged in java.lang
▪ Thread encapsulates a thread of execution.
▪ To create a new thread, your program will either
extend Thread or implement the Runnable
interface.
Creating a thread
▪ You create a thread by instantiating an object of type
Thread.
▪ Java defines two ways in which you can create a
runnable object.
– You can implement the runnable interface
– You can extendThread class.
▪ The runnable interface abstracts a unit of executable
code.
▪ Runnable defines only one method called run(), which is
declared as
▪ public void run()
▪ Inside run(), you have to define the code that
constitutes the new thread.
▪ Run can call other methods, use the classes,
declare variables just like main thread.
▪ It is just an entry point for another, concurrent
thread of execution within your program.
▪ The thread will end when run() returns.
▪ Thread defines several constructors. One of them
is
– Thread(Runnable threadOb)
▪ Once created , the new thread will not start
running until you call its start() method , which is
declared withinThread()
▪ start() executes a to run().
▪ void start()
▪ Here is an example that creates a new thread and
starts running
▪ Inside run() , a loop is established that counts from
0 to 9.
▪ The sleep() method causes the thread from which
it is called to suspend execution for the specified
period of milliseconds.
▪ static void sleep(long milliseconds) throws
Interrupted Exception
output
Creating multiple threads
▪ program can spawn as many threads as it needs.
For example, the following program creates three
child threads
▪ once started, all three child threads share the CPU.
▪ Notice that the threads are started in the order in
which they are created.
▪ However, this may not always be the case.
▪ Java is free to schedule the execution of threads in
its own way.
▪ Of course, because of differences in timing or
environment, the precise output from the program
may differ
Determining When a Thread
Ends
▪ Its useful to know when the thread is ended.
▪ Thread provides two means by which you can
determine if a thread has ended
– isAlive()
– join()
▪ General form of isAlive () is as follows:
▪ final boolean isAlive( )
▪ The isAlive( ) method returns true if the thread upon
which it is called is still running otherwise it returns
false.
isAlive()
Join()
▪ General format of the following function is as
follows:
▪ final void join( ) throws InterruptedException
▪ This method waits till the called method
terminates.
▪ Named as join() since its calling thread waiting
until the specified thread joins it.
▪ Another version of join() is that it takes a maximum
amount of time that you want a specified thread to
wait.
Thread Priorities
▪ Each thread has associated thread priority
▪ In thread priority it determines how much CPU time a thread
receives.
▪ High priority and low priority
▪ It affects in scheduling the threads
▪ Does not mean high priority threads run faster then low
priority threads.
▪ When a child thread starts, its priority is equal to the parent
thread.
▪ Can change the priority by using a function called
setPriority(). General form is as follows
▪ final void setPriority(int level)
▪ level specifies the new priority setting for the calling thread.
▪ The value of level must be within the range MIN_PRIORITY
and MAX_PRIORITY
▪ Currently these values are from 1 to 10.
▪ To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5.
▪ You can obtain the current priority setting by calling the
getPriority( ) method ofThread , shown here:
▪ final int getPriority( )
▪ The following example demonstrates two threads at
different priorities.
▪ The threads are created as instances of Priority. The
run( ) method contains a loop that counts the number
of iterations. The loop stops when either the count
reaches 10,000,000 or the static variable stop is true.
▪ Initially, stop is set to false, but the first thread to finish
counting sets stop to true.
▪ This causes the second thread to terminate with its
next time slice. Each time through the loop
▪ the string in currentName is checked against the name
of the executing thread.
▪ If they don’t match, it means that a task-switch
occurred.
▪ Each time a task-switch happens, the name of the new
thread is displayed, and currentName is given the
name of the new thread.
▪ After both threads stop, the number of iterations for
each loop is displayed
// Demonstrate thread priorities.
class Priority implements Runnable {
int count;
Thread thrd;
static boolean stop = false;
static String currentName;
/* Construct a new thread. Notice that this constructor does not
actually start the threads running. */
Priority(String name) {
thrd = newThread(this, name);
count = 0;
currentName = name;
}
// Begin execution of new thread.
public void run() {
System.out.println(thrd.getName() + " starting.");
do {
count++;
if(currentName.compareTo(thrd.getName()) != 0) {
currentName = thrd.getName();
System.out.println("In " + currentName);
}
} while(stop == false && count < 10000000);
stop = true;
System.out.println("n" + thrd.getName() +" terminating.");
}
}
Synchronization
▪ When using multiple threads, it is sometimes
necessary to coordinate the activities of two or
more. The process by which this is achieved is
called synchronization.
▪ Reason for synchronization:
– When two or more threads need access to a shared
resource that can be used by only one thread at a time.
– When one thread is waiting for an event that is caused by
another thread.
▪ Example: when one thread is writing to a file, a
second thread must be prevented from doing so at
the same time.
▪ Java there is a concept of monitor, it is
implemented by lock.
▪ When an object is locked by one thread, no other
thread can gain access to the object.
▪ When the thread exits, the object is unlocked and
is available for use by another thread.
▪ All objects in Java have a monitor. This feature is
built into the Java language, itself. Thus, all objects
can be synchronized.
▪ Defined by a keyword “synchronized”
▪ There are two ways of synchronizing the threads,
both are discussed below.
Using Synchronized Methods
▪ When that method is called, the calling thread enters the
object’s monitor, which then locks the object.
▪ While locked, no other thread can enter the method, or enter
any other synchronized method defined by the object.
▪ When the thread returns from the method, the monitor
unlocks the object, allowing it to be used by the next thread.
▪ Thus, synchronization is achieved with virtually no
programming effort on your part.
▪ The following program demonstrates
synchronization by controlling access to a method
called sumArray( ), which sums the elements of an
integer array.
If synchronized is removed
Child #1 starting.
Running total for Child #1 is 1
Child #2 starting.
Running total for Child #2 is 1
Running total for Child #1 is 3
Running total for Child #2 is 5
Running total for Child #2 is 8
Running total for Child #1 is 11
Running total for Child #2 is 15
Running total for Child #1 is 19
Running total for Child #2 is 24
Sum for Child #2 is 24
Child #2 terminating.
Running total for Child #1 is 29
Sum for Child #1 is 29
Child #1 terminating
key points of a synchronized
method
▪ A synchronized method is created by preceding its
declaration with synchronized.
▪ For any given object, once a synchronized method
has been called, the object is locked and no
synchronized methods on the same object can be
used by another thread of execution.
▪ Other threads trying to call an in-use synchronized
object will enter a wait state until the object is
unlocked.
▪ When a thread leaves the synchronized method,
the object is unlocked
The synchronized Statement
▪ Although creating synchronized methods within
classes that you create is an easy and effective means
of achieving synchronization, it will not work in all
cases.
▪ This is the general form of a synchronized block:
synchronized(object) {
// statements to be synchronized
}
▪ object is a reference to the object being synchronized. A
synchronized block ensures that a call to a method i.e. a
member of object will take place only after the object’s
monitor has been entered by the calling thread.
Thread Communication Using
notify( ), wait( ), and
notifyAll( )
▪ A thread called T is executing inside a synchronized
method and needs access to a resource called R
that is temporarily unavailable.
▪ If T enters some form of polling loop that waits for
R, T ties up the object, preventing other threads
access to it.
▪ Solution is to have T temporarily relinquish control
of the object, allowing another thread to run.
When R becomes available, T can be notified and
resume execution.
▪ Java supports interthread communication with the wait( ),
notify( ), and notifyAll( ) methods.
▪ When a thread is temporarily blocked from running, it calls
wait( ).
▪ This causes the thread to go to sleep and the monitor for that
object to be released , allowing another thread to use the
object.
▪ At a later point, the sleeping thread is awakened when some
other thread enters the same monitor and calls notify( ), or
notifyAll( ).
▪ A call to notify( ) resumes one thread.
▪ A call to notifyAll( ) resumes all threads, with the highest
priority thread gaining access to the object.
Following are the various forms
of wait( ) defined by Object.
An Example That Uses wait( )
and notify( )
▪ we will create a class called TickTock that contains two
methods:
▪ tick( ) and tock( ).
▪ The tick( ) method displays the word “Tick”, and
tock( ) displays “Tock”.
▪ To run the clock, two threads are created, one that calls
tick( ) and one that calls tock( ).
▪ The goal is to make the two threads execute in a way
that the output from the program displays a consistent
“Tick Tock”—that is, a repeated pattern of one tick
followed by one tock.
Suspending, Resuming,
and Stopping Threads
▪ It is sometimes useful to suspend execution of a
thread.
▪ For example, a separate thread can be used to
display the time of day.
▪ If the user does not desire a clock, then its thread
can be suspended.
▪ Once suspended, it is also a simple matter to
restart the thread.
▪ a program used suspend( ), resume( ), and stop( ),
which are methods defined by Thread, to pause,
restart, and stop the execution of a thread.
▪ final void resume( )
▪ final void suspend( )
▪ final void stop( )
▪ All of the three methods were depreciated in Java2
▪ This was done because they can sometimes cause
serious system failures.
▪ Assume that a thread has obtained locks on critical data
structures.
▪ If that thread is suspended at that point, those locks are
not relinquished. Other threads that may be waiting for
those resources can be deadlocked.
▪ The resume( ) method is also deprecated. It does not
cause problems but cannot be used without the
suspend( ) method as its counterpart.
▪ The stop( ) method of the Thread class was also
deprecated by Java 2. This was done because this
method too can sometimes cause serious system
failures.
▪ thread must be designed so that the run( ) method
periodically checks to determine if that thread should
suspend, resume, or stop its own execution
▪ Typically, this is accomplished by establishing two flag
variables: one for suspend and resume, and one for
stop.
▪ For suspend and resume, as long as the flag is set to
“running,” the run( ) method must continue to let the
thread execute.
▪ If this variable is set to “suspend,” the thread must
pause. For the stop flag, if it is set to “stop,” the thread
must terminate.
▪ The thread class MyThread defines two Boolean variables,
suspended and stopped, which govern the suspension and
termination of a thread.
▪ Both are initialized to false by the constructor. The run( )
method contains a synchronized statement block that checks
suspended.
▪ If that variable is true, the wait( ) method is invoked to
suspend the execution of the thread.
▪ To suspend execution of the thread, call mysuspend( ), which
sets suspended to true. To resume execution, call myresume(
), which sets suspended to false and invokes notify( ) to
restart the thread.
▪ To stop the thread, call mystop( ), which sets stopped to true.
In addition, mystop( ) sets suspended to false and then calls
notify( ). These steps are necessary to stop a suspended
thread.

More Related Content

What's hot

Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharpDeivaa
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 

What's hot (20)

Thread 1
Thread 1Thread 1
Thread 1
 
javathreads
javathreadsjavathreads
javathreads
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
multi threading
multi threadingmulti threading
multi threading
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 

Similar to Chap3 multi threaded programming

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptxsandhyakiran10
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .happycocoman
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreadingssusere538f7
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptxssuserfcae42
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 

Similar to Chap3 multi threaded programming (20)

advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threads
ThreadsThreads
Threads
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreading
MultithreadingMultithreading
Multithreading
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

More from raksharao

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logicraksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inferenceraksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiersraksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofsraksharao
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validationraksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problemsraksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation softwareraksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problemsraksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing modelsraksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problemsraksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationraksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contdraksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introductionraksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architectureraksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletraksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 appletsraksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languagesraksharao
 

More from raksharao (20)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languages
 

Recently uploaded

Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 

Recently uploaded (20)

Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 

Chap3 multi threaded programming

  • 2. contents ▪ Multithreaded fundamentals ▪ The thread class and runnable interface ▪ Creating a thread ▪ Creating multiple threads ▪ Determining when a thread ends ▪ Thread priorities ▪ Synchronization ▪ Using synchronized methods ▪ The synchronized statement ▪ Thread communication using notify(), wait() and notifyall() ▪ Suspending , resuming and stopping threads
  • 3. Introduction ▪ A multithreaded program contains two or more parts that can run concurrently. ▪ Each part of such a program is called thread ▪ Each thread defines a separate path of execution. ▪ Multithreading is a specialized form of multitasking.
  • 4. Multithreading fundamentals ▪ There are two distinct types of multitasking: – Process based – Thread based ▪ A process is a program that is executing ▪ Process –based multitasking is the feature that allows you to run two or more programs concurrently. ▪ Eg.: running Java compiler and editing text in text editor simultaneously.
  • 5. ▪ In thread based multitasking environment, thread is the smallest unit of dispatchable code. ▪ Means a single program can perform two or more tasks at once. ▪ Eg.. Text editor can be formatting text at the same time that is printing.
  • 6. Advantages of multithreading ▪ It enables you to write very efficient programs because it lets you utilize the idle time is present in most programs. ▪ I/O devices such as keyboard, disk drives etc are slower than CPU. Thus program will spend maximum of time in waiting to send or receive information to or from the device. ▪ By using multithreading , your program can execute the another task during the idle time
  • 7. ▪ Eg. When one part of the program is sending a file over the internet, another part can be reading keyboard input, still another can be buffering the next block of data to send. ▪ A thread can be in several states – It can be running. – It can be ready to run as soon it gets CPU time. – A running thread can be suspended, which is temporary halt for execution. – It can be resumed later.
  • 8. – A thread can be blocked when waiting for a resource. – A thread can be terminated, in which case its execution ends and cannot be resumed. ▪ Synchronization: it allows the execution of threads to be coordinated in a certain well defined ways.
  • 9. The thread class and runnable interface ▪ Java’s multithreading system is built upon the Thread class and its companion interface , Runnable. ▪ Both are packaged in java.lang ▪ Thread encapsulates a thread of execution. ▪ To create a new thread, your program will either extend Thread or implement the Runnable interface.
  • 10.
  • 11. Creating a thread ▪ You create a thread by instantiating an object of type Thread. ▪ Java defines two ways in which you can create a runnable object. – You can implement the runnable interface – You can extendThread class. ▪ The runnable interface abstracts a unit of executable code. ▪ Runnable defines only one method called run(), which is declared as ▪ public void run()
  • 12. ▪ Inside run(), you have to define the code that constitutes the new thread. ▪ Run can call other methods, use the classes, declare variables just like main thread. ▪ It is just an entry point for another, concurrent thread of execution within your program. ▪ The thread will end when run() returns. ▪ Thread defines several constructors. One of them is – Thread(Runnable threadOb)
  • 13. ▪ Once created , the new thread will not start running until you call its start() method , which is declared withinThread() ▪ start() executes a to run(). ▪ void start() ▪ Here is an example that creates a new thread and starts running
  • 14.
  • 15.
  • 16. ▪ Inside run() , a loop is established that counts from 0 to 9. ▪ The sleep() method causes the thread from which it is called to suspend execution for the specified period of milliseconds. ▪ static void sleep(long milliseconds) throws Interrupted Exception
  • 18. Creating multiple threads ▪ program can spawn as many threads as it needs. For example, the following program creates three child threads
  • 19.
  • 20.
  • 21. ▪ once started, all three child threads share the CPU. ▪ Notice that the threads are started in the order in which they are created. ▪ However, this may not always be the case. ▪ Java is free to schedule the execution of threads in its own way. ▪ Of course, because of differences in timing or environment, the precise output from the program may differ
  • 22. Determining When a Thread Ends ▪ Its useful to know when the thread is ended. ▪ Thread provides two means by which you can determine if a thread has ended – isAlive() – join() ▪ General form of isAlive () is as follows: ▪ final boolean isAlive( ) ▪ The isAlive( ) method returns true if the thread upon which it is called is still running otherwise it returns false.
  • 24. Join() ▪ General format of the following function is as follows: ▪ final void join( ) throws InterruptedException ▪ This method waits till the called method terminates. ▪ Named as join() since its calling thread waiting until the specified thread joins it. ▪ Another version of join() is that it takes a maximum amount of time that you want a specified thread to wait.
  • 25.
  • 26.
  • 27.
  • 28. Thread Priorities ▪ Each thread has associated thread priority ▪ In thread priority it determines how much CPU time a thread receives. ▪ High priority and low priority ▪ It affects in scheduling the threads ▪ Does not mean high priority threads run faster then low priority threads. ▪ When a child thread starts, its priority is equal to the parent thread.
  • 29. ▪ Can change the priority by using a function called setPriority(). General form is as follows ▪ final void setPriority(int level) ▪ level specifies the new priority setting for the calling thread. ▪ The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY ▪ Currently these values are from 1 to 10. ▪ To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
  • 30. ▪ You can obtain the current priority setting by calling the getPriority( ) method ofThread , shown here: ▪ final int getPriority( ) ▪ The following example demonstrates two threads at different priorities. ▪ The threads are created as instances of Priority. The run( ) method contains a loop that counts the number of iterations. The loop stops when either the count reaches 10,000,000 or the static variable stop is true. ▪ Initially, stop is set to false, but the first thread to finish counting sets stop to true.
  • 31. ▪ This causes the second thread to terminate with its next time slice. Each time through the loop ▪ the string in currentName is checked against the name of the executing thread. ▪ If they don’t match, it means that a task-switch occurred. ▪ Each time a task-switch happens, the name of the new thread is displayed, and currentName is given the name of the new thread. ▪ After both threads stop, the number of iterations for each loop is displayed
  • 32. // Demonstrate thread priorities. class Priority implements Runnable { int count; Thread thrd; static boolean stop = false; static String currentName; /* Construct a new thread. Notice that this constructor does not actually start the threads running. */ Priority(String name) { thrd = newThread(this, name); count = 0; currentName = name; }
  • 33. // Begin execution of new thread. public void run() { System.out.println(thrd.getName() + " starting."); do { count++; if(currentName.compareTo(thrd.getName()) != 0) { currentName = thrd.getName(); System.out.println("In " + currentName); } } while(stop == false && count < 10000000); stop = true; System.out.println("n" + thrd.getName() +" terminating."); } }
  • 34.
  • 35.
  • 36. Synchronization ▪ When using multiple threads, it is sometimes necessary to coordinate the activities of two or more. The process by which this is achieved is called synchronization. ▪ Reason for synchronization: – When two or more threads need access to a shared resource that can be used by only one thread at a time. – When one thread is waiting for an event that is caused by another thread.
  • 37. ▪ Example: when one thread is writing to a file, a second thread must be prevented from doing so at the same time. ▪ Java there is a concept of monitor, it is implemented by lock. ▪ When an object is locked by one thread, no other thread can gain access to the object. ▪ When the thread exits, the object is unlocked and is available for use by another thread.
  • 38. ▪ All objects in Java have a monitor. This feature is built into the Java language, itself. Thus, all objects can be synchronized. ▪ Defined by a keyword “synchronized” ▪ There are two ways of synchronizing the threads, both are discussed below.
  • 39. Using Synchronized Methods ▪ When that method is called, the calling thread enters the object’s monitor, which then locks the object. ▪ While locked, no other thread can enter the method, or enter any other synchronized method defined by the object. ▪ When the thread returns from the method, the monitor unlocks the object, allowing it to be used by the next thread. ▪ Thus, synchronization is achieved with virtually no programming effort on your part.
  • 40. ▪ The following program demonstrates synchronization by controlling access to a method called sumArray( ), which sums the elements of an integer array.
  • 41.
  • 42.
  • 43.
  • 44. If synchronized is removed Child #1 starting. Running total for Child #1 is 1 Child #2 starting. Running total for Child #2 is 1 Running total for Child #1 is 3 Running total for Child #2 is 5 Running total for Child #2 is 8 Running total for Child #1 is 11 Running total for Child #2 is 15 Running total for Child #1 is 19 Running total for Child #2 is 24 Sum for Child #2 is 24 Child #2 terminating. Running total for Child #1 is 29 Sum for Child #1 is 29 Child #1 terminating
  • 45. key points of a synchronized method ▪ A synchronized method is created by preceding its declaration with synchronized. ▪ For any given object, once a synchronized method has been called, the object is locked and no synchronized methods on the same object can be used by another thread of execution. ▪ Other threads trying to call an in-use synchronized object will enter a wait state until the object is unlocked. ▪ When a thread leaves the synchronized method, the object is unlocked
  • 46. The synchronized Statement ▪ Although creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. ▪ This is the general form of a synchronized block: synchronized(object) { // statements to be synchronized } ▪ object is a reference to the object being synchronized. A synchronized block ensures that a call to a method i.e. a member of object will take place only after the object’s monitor has been entered by the calling thread.
  • 47.
  • 48.
  • 49. Thread Communication Using notify( ), wait( ), and notifyAll( ) ▪ A thread called T is executing inside a synchronized method and needs access to a resource called R that is temporarily unavailable. ▪ If T enters some form of polling loop that waits for R, T ties up the object, preventing other threads access to it. ▪ Solution is to have T temporarily relinquish control of the object, allowing another thread to run. When R becomes available, T can be notified and resume execution.
  • 50. ▪ Java supports interthread communication with the wait( ), notify( ), and notifyAll( ) methods. ▪ When a thread is temporarily blocked from running, it calls wait( ). ▪ This causes the thread to go to sleep and the monitor for that object to be released , allowing another thread to use the object. ▪ At a later point, the sleeping thread is awakened when some other thread enters the same monitor and calls notify( ), or notifyAll( ). ▪ A call to notify( ) resumes one thread. ▪ A call to notifyAll( ) resumes all threads, with the highest priority thread gaining access to the object.
  • 51. Following are the various forms of wait( ) defined by Object.
  • 52. An Example That Uses wait( ) and notify( ) ▪ we will create a class called TickTock that contains two methods: ▪ tick( ) and tock( ). ▪ The tick( ) method displays the word “Tick”, and tock( ) displays “Tock”. ▪ To run the clock, two threads are created, one that calls tick( ) and one that calls tock( ). ▪ The goal is to make the two threads execute in a way that the output from the program displays a consistent “Tick Tock”—that is, a repeated pattern of one tick followed by one tock.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57. Suspending, Resuming, and Stopping Threads ▪ It is sometimes useful to suspend execution of a thread. ▪ For example, a separate thread can be used to display the time of day. ▪ If the user does not desire a clock, then its thread can be suspended. ▪ Once suspended, it is also a simple matter to restart the thread. ▪ a program used suspend( ), resume( ), and stop( ), which are methods defined by Thread, to pause, restart, and stop the execution of a thread.
  • 58. ▪ final void resume( ) ▪ final void suspend( ) ▪ final void stop( ) ▪ All of the three methods were depreciated in Java2 ▪ This was done because they can sometimes cause serious system failures.
  • 59. ▪ Assume that a thread has obtained locks on critical data structures. ▪ If that thread is suspended at that point, those locks are not relinquished. Other threads that may be waiting for those resources can be deadlocked. ▪ The resume( ) method is also deprecated. It does not cause problems but cannot be used without the suspend( ) method as its counterpart. ▪ The stop( ) method of the Thread class was also deprecated by Java 2. This was done because this method too can sometimes cause serious system failures.
  • 60. ▪ thread must be designed so that the run( ) method periodically checks to determine if that thread should suspend, resume, or stop its own execution ▪ Typically, this is accomplished by establishing two flag variables: one for suspend and resume, and one for stop. ▪ For suspend and resume, as long as the flag is set to “running,” the run( ) method must continue to let the thread execute. ▪ If this variable is set to “suspend,” the thread must pause. For the stop flag, if it is set to “stop,” the thread must terminate.
  • 61.
  • 62.
  • 63.
  • 64. ▪ The thread class MyThread defines two Boolean variables, suspended and stopped, which govern the suspension and termination of a thread. ▪ Both are initialized to false by the constructor. The run( ) method contains a synchronized statement block that checks suspended. ▪ If that variable is true, the wait( ) method is invoked to suspend the execution of the thread. ▪ To suspend execution of the thread, call mysuspend( ), which sets suspended to true. To resume execution, call myresume( ), which sets suspended to false and invokes notify( ) to restart the thread. ▪ To stop the thread, call mystop( ), which sets stopped to true. In addition, mystop( ) sets suspended to false and then calls notify( ). These steps are necessary to stop a suspended thread.

Editor's Notes

  1. Java