This document discusses multithreading in Java. It begins by explaining the difference between single-threaded and multithreaded programs. A multithreaded program contains two or more threads that can run concurrently. Each thread defines a separate path of execution. The document then covers key aspects of multithreading like creating threads by extending the Thread class or implementing the Runnable interface, starting and controlling threads, thread priorities, synchronization, and inter-thread communication.
Java assigns each thread a priority that determines how that thread should be treated for the others. Thread priorities are integers that specify the relative importance of one thread to another.
A priority is meaningless as an absolute value; a higher priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
This is the twelfth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
nterprocess communication (IPC) is a set of programming interfaces that allow a programmer to coordinate activities among different program processes that can run concurrently in an operating system. This allows a program to handle many user requests at the same time. Since even a single user request may result in multiple processes running in the operating system on the user's behalf, the processes need to communicate with each other. The IPC interfaces make this possible. Each IPC method has its own advantages and limitations so it is not unusual for a single program to use all of the IPC methods.
IPC methods include pipes and named pipes; message queueing;semaphores; shared memory; and sockets.
In this presentation, I am explaining about Threads, types of threads, its advantages and disadvantages, difference between Process and Threads, multithreading and its type.
"Like the ppt if you liked the ppt"
LinkedIn - https://in.linkedin.com/in/prakharmaurya
Java assigns each thread a priority that determines how that thread should be treated for the others. Thread priorities are integers that specify the relative importance of one thread to another.
A priority is meaningless as an absolute value; a higher priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
This is the twelfth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
nterprocess communication (IPC) is a set of programming interfaces that allow a programmer to coordinate activities among different program processes that can run concurrently in an operating system. This allows a program to handle many user requests at the same time. Since even a single user request may result in multiple processes running in the operating system on the user's behalf, the processes need to communicate with each other. The IPC interfaces make this possible. Each IPC method has its own advantages and limitations so it is not unusual for a single program to use all of the IPC methods.
IPC methods include pipes and named pipes; message queueing;semaphores; shared memory; and sockets.
In this presentation, I am explaining about Threads, types of threads, its advantages and disadvantages, difference between Process and Threads, multithreading and its type.
"Like the ppt if you liked the ppt"
LinkedIn - https://in.linkedin.com/in/prakharmaurya
Multithreading and concurrency in androidRakesh Jha
Here you will learn -
What is Multithreading
What is concurrency
Process Vs Thread
Improvements and issues with concurrency
Limits of concurrency gains
Concurrency issues
Threads pools with the Executor Framework
AsyncTask and the UI Thread
Code
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
2. 2
A Single Threaded Program
class ABC
{
….
public void main(..)
{
…
..
}
}
begin
body
end
3. 3
Multithreaded Programming
Java provides built-in support for
multithreaded programming.
A multithreaded program contains two or more
parts that can run concurrently.
Each part of such a program is called a thread,
and each thread defines a separate path of
execution.
Thus, multithreading is a specialized form of
multitasking.
4. 4
A Multithreaded Program
Main Thread
Thread A Thread B Thread C
start start
start
Threads may switch or exchange data/results
5. 5
Single and Multithreaded Processes
Threads are light-weight processes within a process
Single-threaded Process
Single instruction stream Multiple instruction stream
Multiplethreaded Process
Threads of
Execution
Common
Address Space
6. 6
Multitasking
There are two distinct types of multitasking:
process-based and
thread-based
It is important to understand the difference
between the two.
For many users, process-based multitasking is the
more familiar form.
A process is, in essence, a program that is
executing.
Thus, process-based multitasking is the feature
that allows your computer to run two or more
programs concurrently.
7. 7
Process-based Multitasking
For example, process-based multitasking
enables you to run the Java compiler at the
same time that you are using a text editor or
visiting a web site.
In process-based multitasking, a program is the
smallest unit of code that can be dispatched by
the scheduler.
8. 8
Thread-based Multitasking
In a thread-based multitasking environment, the
thread is the smallest unit of dispatchable code.
This means that a single program can perform two
or more tasks simultaneously.
For instance, a text editor can format text at the
same time that it is printing, as long as these two
actions are being performed by two separate
threads.
Thus, process-based multitasking deals with the
“big picture,” and thread-based multitasking
handles the details.
9. 9
Multitasking
Multitasking threads require less overhead
than multitasking processes.
Processes are heavyweight tasks that require
their own separate address spaces.
Interprocess communication is expensive and
limited.
Context switching from one process to another
is also costly.
10. 10
Multitasking
Threads, on the other hand, are lighter weight.
They share the same address space and
cooperatively share the same heavyweight
process.
Interthread communication is inexpensive, and
context switching from one thread to the next
is lower in cost.
While Java programs make use of process-
based multitasking environments, process-
based multitasking is not under Java’s control.
11. 11
Multithreaded Server
For Serving Multiple Clients Concurrently
Server
Threads
Server ProcessClient 1 Process
Client 2 Process
Internet
14. 14
Levels of Parallelism
x LoadCPU
Code-Granularity
Code Item
Large grain
(task level)
Program
Medium grain
(control level)
Function (thread)
Fine grain
(data level)
Loop (Compiler)
Very fine grain
(multiple issue)
With hardware
Task i-l Task i Task i+1
func1 ( )
{
....
....
}
func2 ( )
{
....
....
}
func3 ( )
{
....
....
}
a ( 0 ) =..
b ( 0 ) =..
a ( 1 )=..
b ( 1 )=..
a ( 2 )=..
b ( 2 )=..
+
Sockets/
PVM/MPI
Threads
Compilers
15. 15
What are Threads?
A piece of code that run in concurrent with
other threads.
Each thread is a statically ordered sequence of
instructions.
Threads are being extensively used express
concurrency on both single and
multiprocessors machines.
Programming a task having multiple threads of
control – Multithreading or Multithreaded
Programming.
16. 16
Thread Priorities
Java assigns to each thread a priority that
determines how that thread should be treated
with respect to the others.
Thread priorities are integers that specify the
relative priority of one thread to another.
As an absolute value, a priority is meaningless;
a higher-priority thread doesn’t run any faster
than a lower-priority thread if it is the only
thread running.
17. 17
Context Switch
Instead, a thread’s priority is used to decide when
to switch from one running thread to the next.
This is called a context switch. The rules that
determine when a context switch takes place are
simple:
A thread can voluntarily relinquish control. This is done
by explicitly yielding, sleeping, or blocking on pending
I/O. In this scenario, all other threads are examined,
and the highest-priority thread that is ready to run is
given the CPU.
A thread can be preempted by a higher-priority
thread. In this case, a lower-priority thread that does
not yield the processor is simply preempted-no matter
what it is doing-by a higher-priority thread. Basically, as
soon as a higher-priority thread wants to run, it does.
This is called preemptive multitasking.
18. 18
Synchronization
Because multithreading introduces an
asynchronous behavior to your programs, there
must be a way for you to enforce synchronicity
when you need it.
For example, if you want two threads to
communicate and share a complicated data
structure, such as a linked list, you need some
way to ensure that they don’t conflict with
each other.
That is, you must prevent one thread from
writing data while another thread is in the
middle of reading it.
19. 19
Synchronization
For this purpose, Java implements an elegant twist
on an age-old model of interprocess
synchronization: the monitor.
In Java, there is no class “Monitor”; instead, each
object has its own implicit monitor that is
automatically entered when one of the object’s
synchronized methods is called.
Once a thread is inside a synchronized method, no
other thread can call any other synchronized
method on the same object.
This enables you to write very clear and concise
multithreaded code, because synchronization
support is built into the language.
20. 20
Messaging
After we divide our program into separate threads,
we need to define how they will communicate with
each other.
When programming with some other languages, we
must depend on the operating system to establish
communication between threads.
This, of course, adds overhead.
By contrast, Java provides a clean, low-cost way
for two or more threads to talk to each other, via
calls to predefined methods that all objects have.
Java’s messaging system allows a thread to enter a
synchronized method on an object, and then wait
there until some other thread explicitly notifies it
to come out.
21. 21
The Thread Class and the Runnable
Interface
Java’s multithreading system is built upon the
Thread class, its methods, and its companion
interface, Runnable.
Thread encapsulates a thread of execution.
Since we can’t directly refer to the ethereal
state of a running thread, you will deal with it
through its proxy, the Thread instance that
spawned it.
22. 22
The Thread Class
The Thread class defines several methods that
help manage threads.
Method Meaning
getName() Obtain a thread’s name.
getPriority() Obtain a thread’s priority.
isAlive() Determine if a thread is still running.
join() Wait for a thread to terminate.
run() Entry point for the thread.
sleep() Suspend a thread for a period of time.
start() Start a thread by calling its run method.
23. 23
The Main Thread
When a Java program starts up, one thread
begins running immediately.
This is usually called the main thread of your
program, because it is the one that is executed
when your program begins.
The main thread is important for two reasons:
It is the thread from which other “child”
threads will be spawned.
Often, it must be the last thread to finish
execution because it performs various
shutdown actions.
24. 24
The Main Thread
Although the main thread is created
automatically when your program is started, it
can be controlled through a Thread object.
To do so, you must obtain a reference to it by
calling the method currentThread( ), which is a
public static member of Thread.
Its general form is shown here:
static Thread currentThread( )
Example:
CurrentThreadDemo.java
26. 26
Creating Threads in Java
This can be done in any one of the following
ways:
By Sub Classing Thread Class
By Implementing Runnable
MyThread MyClass
Thread
(objects are threads) (objects with run() body)
Thread Runnable
27. 27
Sub Classing Thread
To create a thread, we need to create a new
class that extends Thread. and then to create
an instance of that class.
The extending class must override the run( )
method, which is the entry point for the new
thread.
It must also call start( ) to begin execution of
the new thread.
Here is the preceding program rewritten to
extend Thread:
29. 29
Implementing Runnable
Runnable abstracts a unit of executable code.
We can construct a thread on any object that
implements Runnable.
To implement Runnable, 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.
It is important to understand that run( ) can call
other methods, use other classes, and declare
variables, just like the main thread can.
30. 30
Implementing Runnable
The only difference is that run( ) establishes
the entry point for another, concurrent thread
of execution within your program.
This thread will end when run( ) returns.
After we create a class that implements
Runnable, we will instantiate an object of type
Thread from within that class.
Thread defines several constructors.
The one that we will use is shown here:
Thread(Runnable threadOb, String
threadName)
32. 32
Can we start a thread twice
No. After starting a thread, it can never be
started again.
If we do so, an IllegalThreadStateException is
thrown.
In such case, thread will run once but for
second time, it will throw exception.
TestThreadTwice.java
33. 33
Can we call run() directly
Yes
Each thread starts in a separate call stack.
Invoking the run() method from main thread,
the run() method goes onto the current call
stack rather than at the beginning of a new call
stack.
TestCallRun.java
35. 35
isAlive( ) and join( )
Often we will want the main thread to finish
last.
We can achieve this by calling sleep() within
main() method, with a long enough delay to
ensure that all child threads terminate prior to
the main thread.
However, this is not a satisfactory solution,
and also it raises a larger question: how can one
thread know when another thread has ended.
For this problem, Thread provides a means
using two methods: isAlive() and join().
36. 36
isAlive()
isAlive() method is used to determine whether
a thread has finished or not.
This method is defined by Thread, and its
general form is:
final boolean isAlive()
The isAlive( ) method returns true if the
thread upon which it is called is still running. It
returns false otherwise.
ThreadisAlive.java
37. 37
join()
While isAlive( ) is occasionally useful, the
method that you will more commonly use to wait
for a thread to finish is called join( ), shown
here:
final void join( ) throws InterruptedException
final void join(long milliseconds)throws
InterruptedException
38. 38
join()
This method waits until the thread on which it
is called terminates.
Its name comes from the concept of the calling
thread waiting until the specified thread joins
it.
Additional forms of join( ) allow you to specify
a maximum amount of time that you want to
wait for the specified thread to terminate.
ThreadJoinDemo.java
39. 39
Thread Priorities
Thread priorities are used by the thread
scheduler to decide when each thread should
be allowed to run.
In theory, over a given period of time, higher-
priority threads get more CPU time than lower-
priority threads.
In practice, the amount of CPU time that a
thread gets often depends on several factors
besides its priority. (For example, how an
operating system implements multitasking can
affect the relative availability of CPU time.)
40. 40
Thread Priorities
To set a thread’s priority, use the setPriority()
method, which is a member of Thread. This is its
general form:
final void setPriority(int level)
Here, level specifies the new priority setting for
the calling thread.
The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.
Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5.
These priorities are defined as static final
variables within Thread.
41. Thread Priorities
We can obtain the current priority setting by
calling the getPriority( ) method of Thread,
shown here:
final int getPriority( )
Example:
ThreadDemo.java
41
42. Synchronization
When two or more threads need access to a
shared resource, they need some way to ensure
that the resource will be used by only one thread
at a time. The process by which this is achieved
is called synchronization.
Key to synchronization is the concept of the
monitor.
A monitor is an object that is used as a mutually
exclusive lock.
42
43. Synchronization
Only one thread can own a monitor at a given
time.
When a thread acquires a lock, it is said to have
entered the monitor.
All other threads attempting to enter the locked
monitor will be suspended until the first thread
exits the monitor.
These other threads are said to be waiting for
the monitor.
A thread that owns a monitor can reenter the
same monitor if it so desires.
43
44. Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
44
45. Thread Synchronization
There are two types of thread
synchronization:
Mutual Exclusive
• Synchronized method
• Synchronized block
• Static Synchronization
Inter-Thread Communication
• Cooperation
45
46. Without Synchronization
In the following example, there is no
synchronization, so output is inconsistent.
Let's see the example:
SynchronizationDemo1.java
46
47. Synchronization Method
If you declare any method as
synchronized, it is known as synchronized
method.
Synchronized method is used to lock an
object for any shared resource.
When a thread invokes a synchronized
method, it automatically acquires the lock
for that object and releases it when the
thread completes its task.
SynchronizationDemo2.java
47
48. Synchronized Block
Synchronized block can be used to perform
synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method,
but you want to synchronize only 5 lines, you can use
synchronized block.
If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
Synchronized block is used to lock an object for any
shared resource.
Scope of synchronized block is smaller than the method.
48
50. Static Synchronization
If you make any static method as synchronized,
the lock will be on the class not on object.
50
51. Static Synchronization
Suppose there are two objects of a shared class(e.g.
Odd) named object1 and object2.
In case of synchronized method and synchronized
block there cannot be interference between t1 and
t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.
But there can be interference between t1 and t3 or
t2 and t4 because t1 acquires another lock and t3
acquires another lock.
We want no interference between t1 and t3 or t2
and t4.
Static synchronization solves this problem.
51
53. Interthread Communication
The preceding examples unconditionally blocked other
threads from asynchronous access to certain methods.
This use of the implicit monitors in Java objects is
powerful, but you can achieve a more subtle level of
control through inter-process communication.
Multithreading replaces event loop programming by
dividing your tasks into discrete, logical units.
Threads also provide a secondary benefit: they do away
with polling.
Polling is usually implemented by a loop that is used to
check some condition repeatedly.
Once the condition is true, appropriate action is taken.
This wastes CPU time.
53
54. Interthread Communication
For example, consider the classic queuing problem,
where one thread is producing some data and
another is consuming it.
To make the problem more interesting, suppose that
the producer has to wait until the consumer is
finished before it generates more data.
In a polling system, the consumer would waste many
CPU cycles while it waited for the producer to
produce.
Once the producer was finished, it would start
polling, wasting more CPU cycles waiting for the
consumer to finish, and so on.
Clearly, this situation is undesirable.
54
55. Interthread Communication
To avoid polling, Java includes an elegant
interprocess communication mechanism via
wait( ),
notify( ), and
notifyAll( ) methods.
These methods are implemented as final
methods in Object, so all classes have them.
All three methods can be called only from within
a synchronized context.
55
56. Interthread Communication
wait( ) tells the calling thread to give up the
monitor and go to sleep until some other thread
enters the same monitor and calls notify( ) or
notifyAll( ).
notify( ) wakes up a thread that called wait( ) on
the same object.
notifyAll( ) wakes up all the threads that called
wait( ) on the same object. One of the threads will
be granted access.
These methods are declared within Object, as shown
here:
final void wait( ) throws InterruptedException
final void notify( )
final void notify All( )
56
57. Interthread Communication
Incorrect implementation of Producer and
Consumer Problem without Interthread
Communication:
PC.java
Correct implementation with Interthread
Communication:
TCDemo.java
57
58. ThreadGroup
Java provides a convenient way to group multiple
threads in a single object.
In such way, we can suspend, resume or interrupt
group of threads by a single method call.
A ThreadGroup represents a set of threads. A
thread group can also include the other thread
group.
The thread group creates a tree in which every
thread group except the initial thread group has a
parent.
A thread is allowed to access information about
its own thread group, but it cannot access the
information about its thread group's parent
thread group or any other thread groups.
58
59. ThreadGroup Constructors
public ThreadGroup(String name):
Constructs a new thread group. The parent
of this new group is the thread group of
the currently running thread.
public ThreadGroup(ThreadGroup parent,
String name): Creates a new thread
group. The parent of this new group is the
specified thread group.
59
60. ThreadGroup Methods
int activeCount(): This method returns the
number of threads in the group plus any
group for which this thread is parent.
int activeGroupCount(): This method returns
an estimate of the number of active groups in
this thread group.
int getMaxPriority(): Returns the maximum
priority setting for the group.
void setMaxPriority(int priority):Sets the
maximum priority of the invoking group to
priority.
60
61. ThreadGroup Methods
ThreadGroup getParent(): Returns null if
the invoking ThreadGroup object has no
parent. Otherwise, it returns the parent of
the invoking object.
void list(): Displays information about the
group.
boolean parentOf(ThreadGroup group): This
method tests if this thread group is either
the thread group argument or one of its
ancestor thread groups.
ThreadGroup getThreadGroup(): This
method returns the ThreadGroup details of
the thread.
61