The document discusses multithreading in Java. It covers the basics of multithreading including main threads, thread life cycles, creating multiple threads, thread priorities, synchronization, and inter-thread communication. It describes the different states a thread can be in like ready, running, blocked, and terminated. It also discusses thread priorities, synchronization techniques using monitors and messaging, and how to implement threads using the Thread class and Runnable interface.
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.
This document provides an overview of multithreading programming in Java. It discusses key concepts like threads, the thread life cycle, creating threads by extending Thread or implementing Runnable, setting thread priorities, and synchronization. Multithreading allows concurrent execution to maximize CPU utilization and is commonly used for games, animations, and other applications requiring parallel processing. Synchronization is needed to prevent issues when multiple threads access shared resources concurrently.
This document discusses threads and multithreading in Java. It defines a thread as the smallest unit of processing and notes that threads are lightweight and execute independently within a process. It covers the Thread class in Java and how to create threads by extending the Thread class or implementing the Runnable interface. The document also discusses thread states, priorities, synchronization, and the advantages of multithreading like improved performance.
This document discusses threads and multithreading in Java. It defines a thread as the smallest unit of processing and notes that threads are lightweight and execute independently within a process. It covers the Thread class in Java and how to create threads by extending the Thread class or implementing the Runnable interface. The document also discusses thread states, priorities, synchronization, and the advantages of multithreading like improved performance.
The document discusses the thread model of Java. It states that all Java class libraries are designed with multithreading in mind. Java uses threads to enable asynchronous behavior across the entire system. Once started, a thread can be suspended, resumed, or stopped. Threads are created by extending the Thread class or implementing the Runnable interface. Context switching allows switching between threads by yielding control voluntarily or through prioritization and preemption. Synchronization is needed when threads access shared resources using monitors implicit to each object. Threads communicate using notify() and wait() methods.
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.
This document provides information about multithreading and I/O in Java. It discusses the Java thread model and how to create threads using the Thread class and Runnable interface. It covers thread states, priorities, synchronization, and inter-thread communication. It also discusses I/O basics in Java including reading from the console using Console, BufferedReader and Scanner, and writing to the console and files.
Multithreading allows a process to be split into multiple threads to allow parallel processing and faster execution. A thread is a sub-division of a process that can run concurrently with other threads. There are two main ways to create threads in Java: by extending the Thread class or implementing the Runnable interface. Threads have lifecycles and states like new, runnable, running, blocked, waiting, and terminated. Synchronization is used to control access to shared resources and prevent interference between threads.
Multithreading allows programs to have multiple threads that can run concurrently. Each thread defines a separate path of execution. Processes are programs that are executing, while threads exist within a process and share its resources. Creating a new thread requires fewer resources than creating a new process. There are two main ways to define a thread - by implementing the Runnable interface or by extending the Thread class.
A thread is an independent path of execution within a Java program. The Thread class in Java is used to create threads and control their behavior and execution. There are two main ways to create threads - by extending the Thread class or implementing the Runnable interface. The run() method contains the code for the thread's task and threads can be started using the start() method. Threads have different states like New, Runnable, Running, Waiting etc during their lifecycle.
Java allows multithreading which means multiple tasks can run concurrently within a single program. Threads go through different life cycle stages from new to runnable to waiting and terminated. Each thread is assigned a priority level but priorities do not guarantee order of execution. New threads can be created by implementing Runnable interface and starting the thread. Synchronization is needed when multiple threads access shared resources to prevent race conditions and ensure only one thread accesses the resource at a time.
Java allows multithreading which means multiple tasks can run concurrently within a single program. A thread goes through different states in its lifecycle from being born to running to termination. Threads can be created by implementing the Runnable interface and overriding the run method. The run method contains the task being performed by the thread. Synchronization is needed when multiple threads access shared resources to prevent race conditions and ensure only one thread accesses the resource at a time.
This presentation will give a brief idea about threads.
This presentation gives you what is required if you are a starter.
This has the lifecycle, multithreading and differences between multithreadind and normal threading.
This presentation even have example programs.
This document discusses Java multithreading. It explains that multithreading allows an application to have multiple points of execution within the same memory space. It outlines how Java supports multithreading through the Thread class and Runnable interface. It also describes concurrency issues that can arise from multithreading, such as race conditions, and how to address them using techniques like synchronized access and locking.
This document discusses Java multithreading. It begins by outlining the objectives of understanding multithreading, Java's mechanism, concurrency issues, and synchronized access. It then explains that multithreading allows multiple threads to run simultaneously within a process's memory space. Finally, it covers key topics like creating and running threads, thread states, priorities, and ensuring thread-safe access to shared resources through synchronization.
This document provides an overview of multithreading in Java. It describes how multithreading allows an application to perform multiple tasks simultaneously through the use of threads. It explains that threads allow applications to remain responsive even when long tasks are being performed. The document outlines how threads work in Java, including how to create threads using the Thread and Runnable classes, the different states threads can be in, and common concurrency issues that can arise with multithreading like race conditions.
This document discusses multithreading in Java. It defines threads as lightweight processes that exist within a process and share its resources. The main thread is executed when a Java program begins. Additional threads can be created by implementing the Runnable interface or extending the Thread class. Synchronization is needed when threads access shared resources to prevent interference. Methods can be synchronized to allow only one thread to access them at a time. The wait(), notify(), and notifyAll() methods allow threads to communicate about locked resources. Deadlocks can occur when threads have a circular dependency on locks. The Java concurrency utilities provide additional tools for multithreaded programming.
Threads : Single and Multitasking, Creating and terminating the thread, Single and Multi tasking
using threads, Deadlock of threads, Thread communication.
The document discusses the thread model of Java. It states that all Java class libraries are designed with multithreading in mind. Java uses threads to enable asynchronous behavior across the entire system. Once started, a thread can be suspended, resumed, or stopped. Threads are created by extending the Thread class or implementing the Runnable interface. Context switching allows switching between threads by yielding control voluntarily or through prioritization and preemption. Synchronization is needed when threads access shared resources using monitors implicit to each object. Threads communicate using notify() and wait() methods.
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.
This document provides information about multithreading and I/O in Java. It discusses the Java thread model and how to create threads using the Thread class and Runnable interface. It covers thread states, priorities, synchronization, and inter-thread communication. It also discusses I/O basics in Java including reading from the console using Console, BufferedReader and Scanner, and writing to the console and files.
Multithreading allows a process to be split into multiple threads to allow parallel processing and faster execution. A thread is a sub-division of a process that can run concurrently with other threads. There are two main ways to create threads in Java: by extending the Thread class or implementing the Runnable interface. Threads have lifecycles and states like new, runnable, running, blocked, waiting, and terminated. Synchronization is used to control access to shared resources and prevent interference between threads.
Multithreading allows programs to have multiple threads that can run concurrently. Each thread defines a separate path of execution. Processes are programs that are executing, while threads exist within a process and share its resources. Creating a new thread requires fewer resources than creating a new process. There are two main ways to define a thread - by implementing the Runnable interface or by extending the Thread class.
A thread is an independent path of execution within a Java program. The Thread class in Java is used to create threads and control their behavior and execution. There are two main ways to create threads - by extending the Thread class or implementing the Runnable interface. The run() method contains the code for the thread's task and threads can be started using the start() method. Threads have different states like New, Runnable, Running, Waiting etc during their lifecycle.
Java allows multithreading which means multiple tasks can run concurrently within a single program. Threads go through different life cycle stages from new to runnable to waiting and terminated. Each thread is assigned a priority level but priorities do not guarantee order of execution. New threads can be created by implementing Runnable interface and starting the thread. Synchronization is needed when multiple threads access shared resources to prevent race conditions and ensure only one thread accesses the resource at a time.
Java allows multithreading which means multiple tasks can run concurrently within a single program. A thread goes through different states in its lifecycle from being born to running to termination. Threads can be created by implementing the Runnable interface and overriding the run method. The run method contains the task being performed by the thread. Synchronization is needed when multiple threads access shared resources to prevent race conditions and ensure only one thread accesses the resource at a time.
This presentation will give a brief idea about threads.
This presentation gives you what is required if you are a starter.
This has the lifecycle, multithreading and differences between multithreadind and normal threading.
This presentation even have example programs.
This document discusses Java multithreading. It explains that multithreading allows an application to have multiple points of execution within the same memory space. It outlines how Java supports multithreading through the Thread class and Runnable interface. It also describes concurrency issues that can arise from multithreading, such as race conditions, and how to address them using techniques like synchronized access and locking.
This document discusses Java multithreading. It begins by outlining the objectives of understanding multithreading, Java's mechanism, concurrency issues, and synchronized access. It then explains that multithreading allows multiple threads to run simultaneously within a process's memory space. Finally, it covers key topics like creating and running threads, thread states, priorities, and ensuring thread-safe access to shared resources through synchronization.
This document provides an overview of multithreading in Java. It describes how multithreading allows an application to perform multiple tasks simultaneously through the use of threads. It explains that threads allow applications to remain responsive even when long tasks are being performed. The document outlines how threads work in Java, including how to create threads using the Thread and Runnable classes, the different states threads can be in, and common concurrency issues that can arise with multithreading like race conditions.
This document discusses multithreading in Java. It defines threads as lightweight processes that exist within a process and share its resources. The main thread is executed when a Java program begins. Additional threads can be created by implementing the Runnable interface or extending the Thread class. Synchronization is needed when threads access shared resources to prevent interference. Methods can be synchronized to allow only one thread to access them at a time. The wait(), notify(), and notifyAll() methods allow threads to communicate about locked resources. Deadlocks can occur when threads have a circular dependency on locks. The Java concurrency utilities provide additional tools for multithreaded programming.
Threads : Single and Multitasking, Creating and terminating the thread, Single and Multi tasking
using threads, Deadlock of threads, Thread communication.
Introduction to Generative AI and Copilot.pdfTechSoup
In this engaging and insightful two-part webinar series, where we will dive into the essentials of generative AI, address key AI concerns, and demonstrate how nonprofits can benefit from using Microsoft’s AI assistant, Copilot, to achieve their goals.
This event series to help nonprofits obtain Copilot skills is made possible by generous support from Microsoft.
How to Manage & Create a New Department in Odoo 18 EmployeeCeline George
In Odoo 18's Employee module, organizing your workforce into departments enhances management and reporting efficiency. Departments are a crucial organizational unit within the Employee module.
ABCs of Bookkeeping for Nonprofits TechSoup.pdfTechSoup
Accounting can be hard enough if you haven’t studied it in school. Nonprofit accounting is actually very different and more challenging still.
Need help? Join Nonprofit CPA and QuickBooks expert Gregg Bossen in this first-time webinar and learn the ABCs of keeping books for a nonprofit organization.
Key takeaways
* What accounting is and how it works
* How to read a financial statement
* What financial statements should be given to the board each month
* What three things nonprofits are required to track
What features to use in QuickBooks to track programs and grants
Himachal Pradesh’s beautiful hills have long faced a challenge: limited access to quality education and career opportunities for students in remote towns and villages. Many young people had to leave their homes in search of better learning and growth, creating a gap between talent and opportunity.
Vikas Bansal, a visionary leader, decided to change this by bringing education directly to the heart of the Himalayas. He founded the Himalayan Group of Professional Institutions, offering courses in engineering, management, pharmacy, law, and more. These institutions are more than just schools—they are centers of hope and transformation.
By introducing digital classrooms, smart labs, and practical workshops, Vikas ensures that students receive modern, high-quality education without needing to leave their hometowns. His skill development programs prepare youth for real-world careers by teaching technical and leadership skills, with strong industry partnerships and hands-on training.
Vikas also focuses on inclusivity, providing scholarships, career counseling, and support to underprivileged and first-generation learners. His quiet but impactful leadership is turning Himachal Pradesh into a knowledge hub, empowering a new generation to build a brighter future right in their own hills.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. In this slide try to present the brief history of Chaulukyas of Gujrat up to Kumarpala To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
Chaulukya or Solanki was one of the Rajputs born from Agnikul. In the Vadnagar inscription, the origin of this dynasty is told from Brahma's Chauluk or Kamandalu. They ruled in Gujarat from the latter half of the tenth century to the beginning of the thirteenth century. Their capital was in Anahilwad. It is not certain whether it had any relation with the Chalukya dynasty of the south or not. It is worth mentioning that the name of the dynasty of the south was 'Chaluky' while the dynasty of Gujarat has been called 'Chaulukya'. The rulers of this dynasty were the supporters and patrons of Jainism.
Completed Sunday 6/8. For Weekend 6/14 & 15th. (Fathers Day Weekend US.) These workshops are also timeless for future students TY. No admissions needed.
A 9th FREE WORKSHOP
Reiki - Yoga
“Intuition-II, The Chakras”
Your Attendance is valued.
We hit over 5k views for Spring Workshops and Updates-TY.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters, we are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
S9/This Week’s Focus:
* A continuation of Intuition-2 Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
Thx for tuning in. Your time investment is valued. I do select topics related to our timeline and community. For those seeking upgrades or Reiki Levels. Stay tuned for our June packages. It’s for self employed/Practitioners/Coaches…
Review & Topics:
* Reiki Is Japanese Energy Healing used Globally.
* Yoga is over 5k years old from India. It hosts many styles, teacher versions, and it’s Mainstream now vs decades ago.
* Anything of the Holistic, Wellness Department can be fused together. My origins are Alternative, Complementary Medicine. In short, I call this ND. I am also a metaphysician. I learnt during the 90s New Age Era. I forget we just hit another wavy. It’s GenZ word of Mouth, their New Age Era. WHOA, History Repeats lol. We are fusing together.
* So, most of you have experienced your Spiritual Awakening. However; The journey wont be perfect. There will be some roller coaster events. The perks are: We are in a faster Spiritual Zone than the 90s. There’s more support and information available.
(See Presentation for all sections, THX AGAIN.)
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
Battle of Bookworms is a literature quiz organized by Pragya, UEM Kolkata, as part of their cultural fest Ecstasia. Curated by quizmasters Drisana Bhattacharyya, Argha Saha, and Aniket Adhikari, the quiz was a dynamic mix of classical literature, modern writing, mythology, regional texts, and experimental literary forms. It began with a 20-question prelim round where ‘star questions’ played a key tie-breaking role. The top 8 teams moved into advanced rounds, where they faced audio-visual challenges, pounce/bounce formats, immunity tokens, and theme-based risk-reward questions. From Orwell and Hemingway to Tagore and Sarala Das, the quiz traversed a global and Indian literary landscape. Unique rounds explored slipstream fiction, constrained writing, adaptations, and true crime literature. It included signature IDs, character identifications, and open-pounce selections. Questions were crafted to test contextual understanding, narrative knowledge, and authorial intent, making the quiz both intellectually rewarding and culturally rich. Battle of Bookworms proved literature quizzes can be insightful, creative, and deeply enjoyable for all.
Exploring Ocean Floor Features for Middle SchoolMarie
This 16 slide science reader is all about ocean floor features. It was made to use with middle school students.
You can download the PDF at thehomeschooldaily.com
Thanks! Marie
How to Manage Multi Language for Invoice in Odoo 18Celine George
Odoo supports multi-language functionality for invoices, allowing you to generate invoices in your customers’ preferred languages. Multi-language support for invoices is crucial for businesses operating in global markets or dealing with customers from different linguistic backgrounds.
Overview of Employee in Odoo 18 - Odoo SlidesCeline George
The employee module is a core component of the HR workspace that helps the business to get the employee activities and details. This would also allow you to get the employee details by acting as a centralized system and accessing, updating, and managing all the other employee data.
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecdrazelitouali
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
THE QUIZ CLUB OF PSGCAS BRINGS T0 YOU A FUN-FILLED, SEAT EDGE BUSINESS QUIZ
DIVE INTO THE PRELIMS OF BIZCOM 2024
QM: GOWTHAM S
BCom (2022-25)
THE QUIZ CLUB OF PSGCAS
2. • Basics of Multithreading
• Main thread
• Thread life cycle
• Creation of multiple threads
• Thread priorities
• Thread synchronization
• Inter-thread communication
• Deadlocks for threads
• Suspending & Resuming threads
3. Basics:
• Unlike many other computer languages, 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.
• You are almost certainly acquainted with multitasking,
because it is supported by virtually all modern operating
systems. However, there are two distinct types of
multitasking: process based and thread-based.
4. Basics: …
• PROCESS-BASED MULTITASKING
• A process is a program that is executing. Thus, process-
based multitasking is the feature that allows our computer
to run two or more programs concurrently.
• For example, process-based multitasking enables you to
run the Java compiler at the same time that you are using a
text editor.
• In process based multitasking, a program is the smallest
unit of code that can be dispatched by the scheduler.
5. Basics: …
• 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.
6. Basics: …
THREAD-BASED vs.PROCESS-BASED 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.
• Threads, on the other hand, are lightweight. 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 low cost.
• While Java programs make use of process based multitasking
environments, process-based multitasking is not under the control of
Java.
7. Basics: …
THREAD-BASED vs.PROCESS-BASED MULTITASKING…
• Multithreading enables you to write very efficient programs that
make maximum use of the CPU, because idle time can be kept to a
minimum. This is especially important for the interactive, networked
environment in which Java operates, because idle time is common.
• For example, the transmission rate of data over a network is much
slower than the rate at which the computer can process it. Even local
file system resources are read and written at a much slower pace than
they can be processed by the CPU.
• And, of course, user input is much slower than the computer. In a
single-threaded environment, our program has to wait for each of
these tasks to finish before it can proceed to the next one—even
though the CPU is sitting idle most of the time. Multithreading lets
you gain access to this idle time and put it to good use.
8. • The Java Thread Model
• The Java run-time system depends on threads for many
things, and all the class libraries are designed with
multithreading in mind. In fact, Java uses threads to enable
the entire environment to be asynchronous. This helps
reduce inefficiency by preventing the waste of CPU cycles.
• The value of a multithreaded environment is best
understood in contrast to its counterpart. Single-threaded
systems use an approach called an event loop with polling.
• The benefit of Java’s multithreading is that the main
loop/polling mechanism is eliminated. One thread can
pause without stopping other parts of your program.
9. • The Java Thread Model ...
• Eg: The idle time created when a thread reads data from a network or waits for
user input can be utilized elsewhere.
• Multithreading allows animation loops to sleep for a second between each frame
without causing the whole system to pause. When a thread blocks in a Java
program, only the single thread that is blocked pauses. All other threads continue to
run.
Advantage of Java Multithreading:
• It doesn't block the user because threads are independent and you
can perform multiple operations at same time.
• You can perform many operations together so it saves time.
• Threads are independent so it doesn't affect other threads if
exception occur in a single thread.
10. • The Java Thread Model ...
• Life Cycle of a Thread:
• Threads exist in several states. Athread can be running.
• It can be ready to run as soon as it gets CPU time.
• A running thread can be suspended, which temporarily suspends
its activity.
• A suspended thread can then be resumed, allowing it to pick up
where it left off.
• Athread can be blocked when waiting for a resource.
• At any time, a thread can be terminated, which halts its
execution immediately.
• Once terminated, a thread cannot be resumed.
11. • The Java Thread Model ...
• Life Cycle of a Thread: ...
12. • The Java Thread Model ...
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.
• 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.
13. • The Java Thread Model ...
Thread Priorities ...
• 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.
14. • The Java Thread Model ...
Thread Priorities ...
• In cases where two threads with the same priority are competing for
CPU cycles, the situation is a bit complicated. For operating systems
such as Windows, threads of equal priority are time-sliced
automatically in round-robin fashion. For other types of operating
systems, threads of equal priority must voluntarily yield control to
their peers. If they don’t, the other threads will not run.
• Java thread priorities are in the range between
MIN_PRIORITY (a constant of 1) and MAX_PRIORITY
(a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
15. • The Java Thread Model ...
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.
• For this purpose, Java implements an elegant twist on an age-old
model of inter-process synchronization: the monitor.
• The monitor is a control mechanism first defined by C.A.R. Hoare.
16. • The Java Thread Model ...
Synchronization ...
• A monitor is a very small box that can hold only one thread. Once a
thread enters a monitor, all other threads must wait until that thread
exits the monitor. In this way, a monitor can be used to protect a
shared asset from being manipulated by more than one thread at a
time.
• Most multithreaded systems expose monitors as objects that your
program must explicitly acquire and manipulate.
• The synchronization is mainly used to,
To prevent thread interference.
To prevent consistency problem.
17. • The Java Thread Model ...
Synchronization ...
• Java provides a cleaner solution. There is
“Monitor”; instead, each object has its own
no class
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.
18. • The Java Thread Model ...
Messaging
• After you divide your program into separate threads, you need to
define how they will communicate with each other. When
programming with most other languages, you 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.
19. • The Java Thread Model ...
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 you 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.
• To create a new thread, your program will either extend
Thread or implement the Runnable interface.
20. • The Java Thread Model ...
The Thread Class and the Runnable Interface ...
• The Thread class defines several methods that help manage threads.
21. • 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.
22. • 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.
• The General form of the method currentThread( )
static Thread currentThread( )
• This method returns a reference to the thread in which it is
called. Once you have a reference to the main thread, you
can control it just like any other thread.
24. • The Main thread ...
• Eg:
• In this program, a reference to the current thread (the main thread, in
this case) is obtained by calling currentThread( ), and this reference
is stored in the local variable t. Next, the program displays
information about the thread. The program then calls setName( ) to
change the internal name of the thread. Information about the thread is
then redisplayed. Next, a loop counts down from five, pausing one
second between each line. The pause is accomplished by the sleep( )
method. The argument to sleep( ) specifies the delay period in
milliseconds. Notice the try/catch block around this loop. The
sleep(
) method in Thread might throw an InterruptedException. This
would happen if some other thread wanted to interrupt this sleeping
one. This example just prints a message if it gets interrupted. In a real
program, you would need to handle this differently.
25. • The Main thread ...
• Eg:
• Notice the output produced when t is used as an argument to
println( ).
• This displays, in order: the name of the thread, its priority, and the
name of its group. By default, the name of the main thread is main.
Its priority is 5, which is the default value, and main is also the
name of the group of threads to which this thread belongs.
• A thread group is a data structure that controls the state of a
collection of threads as a whole.
• After the name of the thread is changed, t is again output. This
time, the new name of the thread is displayed.
26. • Thread life cycle
• As the process has several states, similarly a thread exists in several states. A thread can be in the
following states:
✓ Ready to run (New): First time as soon as it gets CPU time.
✓ Running: Under execution.
✓ Suspended: Temporarily not active or under execution.
✓ Blocked: Waiting for resources.
✓ Resumed: Suspended thread resumed, and start from where it left off.
✓ Terminated: Halts the execution immediately and never resumes.
27. • Creating a Thread
➢ Implementing Runnable
➢ Extending Thread
➢ Choosing anApproach
Creating a Thread
• One can create a thread by instantiating an object
of type Thread.
• Java defines two ways in which thread can be
accomplished: by implementing the Runnable
interface and by extending the Thread class.
28. • Creating a Thread ...
Implementing Runnable:
• The easiest way to create a thread is to create a class that
implements the Runnable interface.
• Runnable abstracts a unit of executable code. You 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( )
29. • Creating a Thread ...
Implementing Runnable: ...
• Inside run( ), you 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.
• 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 you create a class that implements Runnable, you 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)
30. • Creating a Thread ...
Implementing Runnable: ...
• After the new thread is created, it will not start running until you call
its start( ) method, which is declared within Thread. In essence,
start( ) executes a call to run( ).
• The start( ) method is shown here: void start( )
31. • Creating a Thread ...
Implementing Runnable: ...
32. • Creating a Thread ...
Extending Thread:
• The second way to create a thread is 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.
34. • Creating a Thread ...
Choosing anApproach:
• At this point, you might be wondering why Java has two ways to create child
threads, and which approach is better. The answers to these questions turn on the
same point.
• The Thread class defines several methods that can be overridden by
a derived class. Of these methods, the only one that must be
overridden is run( ). This is, of course, the same method required
when you implement Runnable.
• Many Java programmers feel that classes should be extended only
when they are being enhanced or modified in some way. So, if you
will not be overriding any of Thread’s other methods, it is probably
best simply to implement Runnable.
36. • Using isAlive( ) and join( )
• How can one thread know when another thread has ended?
Fortunately, Thread provides a means by which you can
answer this question. Two ways exist to determine whether
a thread has finished.
• First, you can call isAlive( ) on the thread. This method is
defined by Thread, and its general form is shown here:
final boolean isAlive( )
• The isAlive( ) method returns true if the thread upon which
it is called is still running. It returns false otherwise.
37. • Using isAlive( ) and 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
• 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.
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
MIN_PRIORITY
of level
and
must be within the range
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 ariables within Thread.
• To obtain the current priority setting by calling the getPriority( )
method of Thread, shown here: final int getPriority( )
42. • Thread 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.
• If you have worked with synchronization when using other languages, such as C or
C++, you know that it can be a bit tricky to use. This is because these languages do
not, themselves, support synchronization. Instead, to synchronize threads, your
programs need to utilize operating system primitives.
• Fortunately, because Java implements synchronization
through language elements, most of the complexity
associated with synchronization has been eliminated. You
can synchronize your code in either of two ways. Both
involve the use of the synchronized keyword.
43. • Thread synchronization ...
Using Synchronized Methods:
• Synchronization is easy in Java, because all objects have
their own implicit monitor associated with them.
• To enter an object’s monitor, just call a method that has
been modified with the synchronized keyword.
• While a thread is inside a synchronized method, all other
threads that try to call it (or any other synchronized
method) on the same instance have to wait.
• To exit the monitor and relinquish control of the object to
the next waiting thread, the owner of the monitor simply
returns from the synchronized method.
45. • Thread synchronization ...
Using Synchronized Methods: ...
• To fix the preceding program, you must serialize access to call( ).
That is, you must restrict its access to only one thread at a time.
• To do this, you simply need to precede call( )’s definition
• with the keyword synchronized, as shown here:
class Callme {
synchronized void call(String msg) {
...
• This prevents other threads from entering call( ) while another thread
is using it. After synchronized has been added to call( ), the output
of the program is as follows:
[Hello]
[Synchronized]
[World]
46. • Thread synchronization ...
Using Synchronized Methods: ...
• Any time that you have a method, or group of methods,
that manipulates the internal state of an object in a
multithreaded situation, you should use the
synchronized keyword to guard the state from race
conditions.
• Remember, once a thread enters any synchronized
method on an instance, no other thread can enter any
other synchronized method on the same instance.
• However, nonsynchronized methods on that instance
will continue to be callable.
47. • Thread synchronization ...
The synchronized Statement:
• While creating synchronized methods within classes that you create is an
easy and effective means of achieving synchronization, it will not work in
all cases.
• To understand why, consider the following. Imagine that you want to
synchronize access to objects of a class that was not designed for
multithreaded access. That is, the class does not use synchronized
methods.
• Further, this class was not created by you, but by a third party, and you do
not have access to the source code. Thus, you can’t add synchronized to
the appropriate methods within the class.
• How can access to an object of this class be synchronized?
Fortunately, the solution to this problem is quite easy: You simply
put calls to the methods defined by this class inside a
synchronized block.
48. • Thread synchronization ...
The synchronized Statement: ...
• This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized.
• A synchronized block ensures that a call to a method that is
a member of object occurs only after the current thread has
successfully entered object’s monitor.
50. • Inter-thread communication
• Inter-thread communication or Co-operation is all
about allowing synchronized threads to communicate with
each other.
• Cooperation (Inter-thread communication) is a mechanism
in which a thread is paused running in its critical section
and another thread is allowed to enter (or lock) in the same
critical section to be executed.
• It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
51. • Inter-thread communication ...
• These methods have been implemented as final methods in
Object, so they are available in all the classes.
• All three methods can be called only from within a
synchronized context.
53. • Deadlocks for threads
• Deadlock in java is a part of multithreading. Deadlock can occur in
a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are
waiting for each other to release the lock, the condition is called
deadlock.
• Deadlock describes a situation where two or more threads are
blocked forever, waiting for each other. Deadlock occurs when
multiple threads need the same locks but obtain them in different
order. A Java multithreaded program may suffer from the
deadlock condition because the synchronized keyword
causes the executing thread to block while waiting for the
lock, or monitor, associated with the specified object.
54. • Deadlocks for threads ...Deadlock Situation
When you compile and execute above
program, you find a deadlock situation
and below is the output produced by the
program:
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waitingfor lock 2...
Thread 2: Waitingfor lock 1...
The program will hang forever because
neither of the threads in position to
proceed and waiting for each other to
release the lock, so you can come out of
the program by pressing CTRL-C.
55. • Deadlocks for threads ... Solution
So just changing the order of the locks
prevent the program in going deadlock
situation and completes with the
following result:
Thread 1: Holding lock 1...
Thread 1: Waitingfor lock 2...
Thread 1: Holding lock 1 & 2...
Thread 2: Holding lock 1...
Thread 2: Waitingfor lock 2...
Thread 2: Holding lock 1 & 2...
56. • Suspending & Resuming threads /
Suspending, Resuming, and Stopping Threads
• Core Java provides a complete control over multithreaded program.
You can develop a multithreaded program which can be suspended,
resumed or stopped completely based on your requirements.
• There are various static methods which you can use on thread objects
to control their behavior.
58. • Using Multithreading
• The key to utilizing Java’s multithreading features
effectively is to think concurrently rather than serially. For
example, when you have two subsystems within a program
that can execute concurrently, make them individual
threads.
• With the careful use of multithreading, you can create very
efficient programs. A word of caution is in order, however:
If you create too many threads, you can actually degrade
the performance of your program rather than enhance it.
• Remember, some overhead is associated with context
switching. If you create too many threads, more CPU time
will be spent changing contexts than executing your program!