Packages allow organization of classes and import statements. Package statements declare the package a class belongs to and import statements allow referring to classes in other packages. The compiler uses package and import statements to find classes.
Reader and writer classes provide character-based input/output and are built upon stream classes. FileReader and FileWriter allow reading and writing of character files but performance can be improved by wrapping them in buffered classes like BufferedReader and BufferedWriter. PrintWriter is also commonly used for writing and provides additional functionality.
Packages allow organization of classes and import statements. Package statements declare the package a file belongs to while import statements allow referring to classes from other packages without their fully qualified names. The compiler searches jar files and the classpath to locate classes.
Multithreading allows concurrent execution through threads which are lightweight subtasks that run within a process. Creating a thread can be done by extending Thread class and overriding run() or implementing Runnable interface. Threads make programs scalable and allow asynchronous event-driven programming.
Java I/O uses streams for sequential input/output. Reader/Writer classes provide character-based I/O. File and filter streams provide access to files. Buffered streams improve performance of unbuffered streams
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
The document discusses Java performance and threading. It provides an overview of performance concepts, the performance process, and measurement techniques like benchmarking and profiling. It also covers key threading concepts like thread states, synchronization, and how to share data across threads using synchronized methods, objects, and wait/notify.
This document discusses multithreading and generic programming in Java. It covers thread concepts like thread life cycle, creating threads by extending Thread class and implementing Runnable interface. It provides examples of multithreading in applications. Generic programming concepts like generic classes and methods are also briefly introduced. The key outcomes are to develop Java applications using threads and generics.
TCP sockets allow for communication between applications over the internet. A server creates a ServerSocket to listen for incoming connections on a specific port. When a client connects, the server accepts the connection to get a Socket. Both client and server then obtain input and output streams from the Socket to send and receive data. The connection is closed once communication is complete. Multithreading allows servers to handle multiple clients concurrently by spawning a new thread for each connection.
This document discusses multithreading in Java. It defines two types of multitasking: process-based and thread-based. Process-based multitasking allows multiple programs to run concurrently, while thread-based multitasking allows a single program to perform multiple tasks simultaneously by dividing the program into threads. The document describes how to create threads by implementing the Runnable interface or extending the Thread class, and how threads can be scheduled using priorities.
The document discusses threads and multithreading in Java. It defines a thread as a single sequential flow of control that runs within the address space of a process. It notes that threads allow programs to accomplish multiple simultaneous tasks. The document then covers thread states, priorities, synchronization, and provides examples of a producer-consumer problem implemented with and without synchronization.
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.
This document provides information on multithreading, networking, and other Java concepts. It discusses how to create threads in Java by extending the Thread class or implementing Runnable, and describes methods like sleep(), wait(), notify() etc. It also covers networking topics like sockets, servers, clients and protocols. Examples of socket programming and a chatting program using sockets are included. Finally, it discusses classes like URL, URLConnection and HttpURLConnection for working with URLs.
At a time when Herbt Sutter announced to everyone that the free lunch is over (The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software), concurrency has become our everyday life.A big change is coming to Java, the Loom project and with it such new terms as "virtual thread", "continuations" and "structured concurrency". If you've been wondering what they will change in our daily work or
whether it's worth rewriting your Tomcat-based application to super-efficient reactive Netty,or whether to wait for Project Loom? This presentation is for you.
I will talk about the Loom project and the new possibilities related to virtual wattles and "structured concurrency". I will tell you how it works and what can be achieved and the impact on performance
This document provides an overview of concurrency and multi-threading concepts in Java. It defines processes and threads, explaining that threads exist within processes and allow for more efficient concurrent execution than multiple processes. The document reviews object-oriented concepts in Java and introduces threads and multi-threading, describing how to create threads by extending Thread or implementing Runnable. It also outlines the Thread class and common thread states like ready, running, blocked, and dead.
This document discusses multithreading and concurrency in .NET. It covers key concepts like processes and threads, and how they relate on an operating system level. It also discusses the Thread Pool, Task Parallel Library (TPL), Tasks, Parallel LINQ (PLINQ), and asynchronous programming patterns in .NET like async/await. Examples are provided for common threading techniques like producer/consumer and using the Timer class. Overall it serves as a comprehensive overview of multithreading and concurrency primitives available in the .NET framework.
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 multithreaded programming in Java. It describes that a multithreaded program contains two or more parts that can run concurrently as separate execution paths called threads. Threads are lighter weight than processes and allow for more efficient CPU usage by enabling idle time to be minimized. The Java threading model eliminates the single event loop of single-threaded programs by allowing threads to run independently such that if one thread blocks, other threads can continue running. Threads can be created by implementing the Runnable interface or extending the Thread class.
Java was one of the first mainstream programming languages to include threading support within the language itself. This paved the way for Java to become widely used for writing server applications. Every Java program has at least one thread - the main thread. Additional threads are created by the JVM for garbage collection and other tasks. Threads allow programs to take advantage of multi-processor systems and provide more responsive user interfaces by handling long-running processes in background threads.
The document discusses Java Beans, Applets, JDBC, Networking in Java, JNDI, and some key classes used in these technologies. It provides an overview of concepts like Java Beans components, properties, events, introspection, customization, persistence. It describes the lifecycle and methods of Applets. It outlines the basic steps to use JDBC like loading drivers, establishing connections, executing queries. It discusses connection-oriented and connectionless networking in Java and common network classes like Socket, ServerSocket, URL, URLConnection. It provides a high-level overview of the JNDI architecture.
This document provides a brief overview of concurrency concepts in Python, focusing on threading. It defines processes and threads, explaining that threads run within a process and can share resources, while processes are independent and communicate via interprocess communication. It discusses why to use concurrency for performance, responsiveness, and non-blocking behavior. It also covers the Global Interpreter Lock in Python and its implications for threading, and provides examples of creating and running threads.
Threads in java, Multitasking and Multithreadingssusere538f7
Threads allow Java programs to take advantage of multiprocessor systems by performing multiple tasks simultaneously. There are two main ways to create threads in Java - by extending the Thread class or implementing the Runnable interface. Threads can be started using the start() method and terminate when their run() method completes. The Java scheduler uses priority to determine which runnable threads get CPU time, with higher priority threads preempting lower priority ones. Threads provide concurrency but not true parallelism since Java threads still run on one CPU.
This document discusses Java threads and synchronization. It begins with an introduction to threads, defining a thread as a single sequential flow of control within a program. It then covers how to define and launch threads in Java by extending the Thread class or implementing the Runnable interface. The life cycle of a Java thread is explained, including the various thread states. Methods for interrupting threads and thread synchronization using synchronized methods and statements are discussed. Finally, Java's monitor model for thread synchronization is described.
This document discusses operating systems and multi-threading. It begins with an agenda that covers threads, multi-threading models, and multi-threading programming. It then defines threads and processes, and discusses the benefits and disadvantages of using threads. Examples are provided of single-threaded and multi-threaded processes. Finally, it covers thread libraries, thread creation, termination, and joining threads.
This document discusses multithreading and concurrency in Java. It defines a thread as a single sequential flow of control within a program. Multithreading allows a single processor to run multiple threads concurrently by rapidly switching between them. Creating threads in Java involves either extending the Thread class or implementing the Runnable interface. The document outlines thread states like new, ready, running, blocked, and finished. It also discusses thread scheduling, priorities, synchronization to prevent race conditions, and thread pools for managing tasks.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Ad
More Related Content
Similar to JAVA MULTITHREDED PROGRAMMING - LECTURES (20)
The document discusses threads and multithreading in Java. It defines a thread as a single sequential flow of control that runs within the address space of a process. It notes that threads allow programs to accomplish multiple simultaneous tasks. The document then covers thread states, priorities, synchronization, and provides examples of a producer-consumer problem implemented with and without synchronization.
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.
This document provides information on multithreading, networking, and other Java concepts. It discusses how to create threads in Java by extending the Thread class or implementing Runnable, and describes methods like sleep(), wait(), notify() etc. It also covers networking topics like sockets, servers, clients and protocols. Examples of socket programming and a chatting program using sockets are included. Finally, it discusses classes like URL, URLConnection and HttpURLConnection for working with URLs.
At a time when Herbt Sutter announced to everyone that the free lunch is over (The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software), concurrency has become our everyday life.A big change is coming to Java, the Loom project and with it such new terms as "virtual thread", "continuations" and "structured concurrency". If you've been wondering what they will change in our daily work or
whether it's worth rewriting your Tomcat-based application to super-efficient reactive Netty,or whether to wait for Project Loom? This presentation is for you.
I will talk about the Loom project and the new possibilities related to virtual wattles and "structured concurrency". I will tell you how it works and what can be achieved and the impact on performance
This document provides an overview of concurrency and multi-threading concepts in Java. It defines processes and threads, explaining that threads exist within processes and allow for more efficient concurrent execution than multiple processes. The document reviews object-oriented concepts in Java and introduces threads and multi-threading, describing how to create threads by extending Thread or implementing Runnable. It also outlines the Thread class and common thread states like ready, running, blocked, and dead.
This document discusses multithreading and concurrency in .NET. It covers key concepts like processes and threads, and how they relate on an operating system level. It also discusses the Thread Pool, Task Parallel Library (TPL), Tasks, Parallel LINQ (PLINQ), and asynchronous programming patterns in .NET like async/await. Examples are provided for common threading techniques like producer/consumer and using the Timer class. Overall it serves as a comprehensive overview of multithreading and concurrency primitives available in the .NET framework.
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 multithreaded programming in Java. It describes that a multithreaded program contains two or more parts that can run concurrently as separate execution paths called threads. Threads are lighter weight than processes and allow for more efficient CPU usage by enabling idle time to be minimized. The Java threading model eliminates the single event loop of single-threaded programs by allowing threads to run independently such that if one thread blocks, other threads can continue running. Threads can be created by implementing the Runnable interface or extending the Thread class.
Java was one of the first mainstream programming languages to include threading support within the language itself. This paved the way for Java to become widely used for writing server applications. Every Java program has at least one thread - the main thread. Additional threads are created by the JVM for garbage collection and other tasks. Threads allow programs to take advantage of multi-processor systems and provide more responsive user interfaces by handling long-running processes in background threads.
The document discusses Java Beans, Applets, JDBC, Networking in Java, JNDI, and some key classes used in these technologies. It provides an overview of concepts like Java Beans components, properties, events, introspection, customization, persistence. It describes the lifecycle and methods of Applets. It outlines the basic steps to use JDBC like loading drivers, establishing connections, executing queries. It discusses connection-oriented and connectionless networking in Java and common network classes like Socket, ServerSocket, URL, URLConnection. It provides a high-level overview of the JNDI architecture.
This document provides a brief overview of concurrency concepts in Python, focusing on threading. It defines processes and threads, explaining that threads run within a process and can share resources, while processes are independent and communicate via interprocess communication. It discusses why to use concurrency for performance, responsiveness, and non-blocking behavior. It also covers the Global Interpreter Lock in Python and its implications for threading, and provides examples of creating and running threads.
Threads in java, Multitasking and Multithreadingssusere538f7
Threads allow Java programs to take advantage of multiprocessor systems by performing multiple tasks simultaneously. There are two main ways to create threads in Java - by extending the Thread class or implementing the Runnable interface. Threads can be started using the start() method and terminate when their run() method completes. The Java scheduler uses priority to determine which runnable threads get CPU time, with higher priority threads preempting lower priority ones. Threads provide concurrency but not true parallelism since Java threads still run on one CPU.
This document discusses Java threads and synchronization. It begins with an introduction to threads, defining a thread as a single sequential flow of control within a program. It then covers how to define and launch threads in Java by extending the Thread class or implementing the Runnable interface. The life cycle of a Java thread is explained, including the various thread states. Methods for interrupting threads and thread synchronization using synchronized methods and statements are discussed. Finally, Java's monitor model for thread synchronization is described.
This document discusses operating systems and multi-threading. It begins with an agenda that covers threads, multi-threading models, and multi-threading programming. It then defines threads and processes, and discusses the benefits and disadvantages of using threads. Examples are provided of single-threaded and multi-threaded processes. Finally, it covers thread libraries, thread creation, termination, and joining threads.
This document discusses multithreading and concurrency in Java. It defines a thread as a single sequential flow of control within a program. Multithreading allows a single processor to run multiple threads concurrently by rapidly switching between them. Creating threads in Java involves either extending the Thread class or implementing the Runnable interface. The document outlines thread states like new, ready, running, blocked, and finished. It also discusses thread scheduling, priorities, synchronization to prevent race conditions, and thread pools for managing tasks.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Cloud Platform Architecture over Virtualized Datacenters: Cloud Computing and
Service Models, Data Center Design and Interconnection Networks, Architectural Design of Compute and Storage Clouds, Public Cloud Platforms: GAE, AWS and Azure, Inter-Cloud
Resource Management.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
https://www.infopitaara.in/
Data Structures_Linear Data Structure Stack.pptxRushaliDeshmukh2
LIFO Principle,
Stack as an ADT,
Representation and Implementation of Stack using Sequential and Linked Organization.
Applications of Stack- Simulating Recursion using Stack,
Arithmetic Expression Conversion and Evaluation,
Reversing a String.
Time complexity analysis of Stack operations
Dear SICPA Team,
Please find attached a document outlining my professional background and experience.
I remain at your disposal should you have any questions or require further information.
Best regards,
Fabien Keller
Interfacing PMW3901 Optical Flow Sensor with ESP32CircuitDigest
Learn how to connect a PMW3901 Optical Flow Sensor with an ESP32 to measure surface motion and movement without GPS! This project explains how to set up the sensor using SPI communication, helping create advanced robotics like autonomous drones and smart robots.
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
How to Buy Snapchat Account A Step-by-Step Guide.pdfjamedlimmk
Scaling Growth with Multiple Snapchat Accounts: Strategies That Work
Operating multiple Snapchat accounts isn’t just a matter of logging in and out—it’s about crafting a scalable content strategy. Businesses and influencers who master this can turn Snapchat into a lead generation engine.
Key strategies include:
Content Calendars for Each Account – Plan distinct content buckets and themes per account to avoid duplication and maintain variety.
Geo-Based Content Segmentation – Use location-specific filters and cultural trends to speak directly to a region's audience.
Audience Mapping – Tailor messaging for niche segments: Gen Z, urban youth, gamers, shoppers, etc.
Metrics-Driven Storytelling – Use Snapchat Insights to monitor what type of content performs best per account.
Each account should have a unique identity but tie back to a central brand voice. This balance is crucial for brand consistency while leveraging the platform’s creative freedoms.
How Agencies and Creators Handle Bulk Snapchat Accounts
Digital agencies and creator networks often manage dozens—sometimes hundreds—of Snapchat accounts. The infrastructure to support this requires:
Dedicated teams for each cluster of accounts
Cloud-based mobile device management (MDM) systems
Permission-based account access for role clarity
Workflow automation tools (Slack, Trello, Notion) for content coordination
This is especially useful in verticals such as music promotion, event marketing, lifestyle brands, and political outreach, where each campaign needs targeted messaging from different handles.
The Legality and Risk Profile of Bulk Account Operations
If your aim is to operate or acquire multiple Snapchat accounts, understand the risk thresholds:
Personal Use (Low Risk) – One or two accounts for personal and creative projects
Business Use (Medium Risk) – Accounts with aligned goals, managed ethically
Automated Bulk Use (High Risk) – Accounts created en masse or used via bots are flagged quickly
Snapchat uses advanced machine learning detection for unusual behavior, including:
Fast switching between accounts from the same IP
Identical Snap stories across accounts
Rapid follower accumulation
Use of unverified devices or outdated OS versions
To stay compliant, use manual operations, vary behavior, and avoid gray-market account providers.
Smart Monetization Through Multi-Account Snapchat Strategies
With a multi-account setup, you can open doors to diversified monetization:
Affiliate Marketing – Niche accounts promoting targeted offers
Sponsored Content – Brands paying for story placement across multiple profiles
Product Launch Funnels – Segment users by interest and lead them to specific landing pages
Influencer Takeovers – Hosting creators across multiple themed accounts for event buzz
This turns your Snapchat network into a ROI-driven asset instead of a time sink.
Conclusion: Build an Ecosystem, Not Just Accounts
When approached correctly, multiple Snapchat accounts bec
How to Buy Snapchat Account A Step-by-Step Guide.pdfjamedlimmk
Ad
JAVA MULTITHREDED PROGRAMMING - LECTURES
1. Multithreading in Java
Nelson Padua-Perez
Bill Pugh
Department of Computer Science
University of Maryland, College Park
2. Problem
Multiple tasks for computer
Draw & display images on screen
Check keyboard & mouse input
Send & receive data on network
Read & write files to disk
Perform useful computation (editor, browser, game)
How does computer do everything at once?
Multitasking
Multiprocessing
3. Multitasking (Time-Sharing)
Approach
Computer does some work on a task
Computer then quickly switch to next task
Tasks managed by operating system (scheduler)
Computer seems to work on tasks concurrently
Can improve performance by reducing waiting
6. Perform Multiple Tasks Using…
Process
Definition – executable program loaded in memory
Has own address space
Variables & data structures (in memory)
Each process may execute a different program
Communicate via operating system, files, network
May contain multiple threads
7. Perform Multiple Tasks Using…
Thread
Definition – sequentially executed stream of
instructions
Shares address space with other threads
Has own execution context
Program counter, call stack (local variables)
Communicate via shared access to data
Multiple threads in process execute same program
Also known as “lightweight process”
8. Web Server uses
threads to handle …
Multiple simultaneous
web browser requests
Motivation for Multithreading
Captures logical structure of problem
May have concurrent interacting components
Can handle each component using separate thread
Simplifies programming for problem
Example
9. Multiple simultaneous
web browser requests…
Handled faster by
multiple web servers
Motivation for Multithreading
Better utilize hardware resources
When a thread is delayed, compute other threads
Given extra hardware, compute threads in parallel
Reduce overall execution time
Example
10. Multithreading Overview
Motivation & background
Threads
Creating Java threads
Thread states
Scheduling
Synchronization
Data races
Locks
Wait / Notify
11. Programming with Threads
Concurrent programming
Writing programs divided into independent tasks
Tasks may be executed in parallel on multiprocessors
Multithreading
Executing program with multiple threads in parallel
Special form of multiprocessing
12. Creating Threads in Java
You have to specify the work you want the
thread to do
Define a class that implements the Runnable
interface
public interface Runnable {
public void run();
}
Put the work in the run method
Create an instance of the worker class and
create a thread to run it
or hand the worker instance to an executor
13. Thread Class
public class Thread {
public Thread(Runnable R); // Thread R.run()
public Thread(Runnable R, String name);
public void start(); // begin thread execution
...
}
14. More Thread Class Methods
public class Thread {
…
public String getName();
public void interrupt();
public boolean isAlive();
public void join();
public void setDaemon(boolean on);
public void setName(String name);
public void setPriority(int level);
public static Thread currentThread();
public static void sleep(long milliseconds);
public static void yield();
}
15. Creating Threads in Java
Runnable interface
Create object implementing Runnable interface
Pass it to Thread object via Thread constructor
Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread t = new Thread(new MyT()); // create thread
t.start(); // begin running thread
… // thread executing in parallel
16. Alternative (Not Recommended)
Directly extend Thread class
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT t = new MyT(); // create thread
t.start(); // begin running thread
17. Why not recommended?
Not a big problem for getting started
but a bad habit for industrial strength development
The methods of the worker class and the
Thread class get all tangled up
Makes it hard to migrate to Thread Pools and
other more efficient approaches
18. Threads – Thread States
Java thread can be in one of these states
New – thread allocated & waiting for start()
Runnable – thread can execute
Blocked – thread waiting for event (I/O, etc.)
Terminated – thread finished
Transitions between states caused by
Invoking methods in class Thread
start(), yield(), sleep()
Other (external) events
Scheduler, I/O, returning from run()…
19. Threads – Thread States
State diagram
runnable
new
terminated
blocked
new start
terminate
IO, sleep, join,
request lock
IO complete,
sleep expired,
join complete,
acquire lock
20. Threads – Scheduling
Scheduler
Determines which runnable threads to run
Can be based on thread priority
Part of OS or Java Virtual Machine (JVM)
Many computers can run multiple threads
simultaneously (or nearly so)
21. Java Thread Example
public class ThreadExample implements Runnable {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
}
public static void main(String[] args) {
new Thread(new ThreadExample()).start();
new Thread( new ThreadExample()).start();
System.out.println("Done");
}
}
23. Daemon Threads
Why doesn’t the program quit as soon as Done is
printed?
Java threads types
User
Daemon
Provide general services
Typically never terminate
Call setDaemon() before start()
Program termination
If all non-daemon threads terminate, JVM shuts down
24. Might not see different interleavings
The threads in that example are too short
Each started thread will probably complete
before the next thread starts
Let’s make more threads that run longer
25. Data Races
public class DataRace implements Runnable {
static volatile int x;
public void run() {
for (int i = 0; i < 10000; i++) {
x++;
x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x not always 0!
}
}
26. Why volatile
We’ll spend more time on volatile later
But volatile tells the compiler:
other threads might see reads/writes of this variable
don’t change/reorder eliminate the reads and writes
An optimizing compiler should, if it sees
x++; x--;
replace it with a no-op
if x isn’t volatile
27. Thread Scheduling Observations
Order thread is selected is indeterminate
Depends on scheduler, timing, chance
Scheduling is not guaranteed to be fair
Some schedules/interleavings can cause
unexpected and bad behaviors
Synchronization
can be used to control thread execution order
28. Using Synchronization
public class DataRace implements Runnable {
static volatile int x;
static Object lock = new Object();
public void run() {
for (int i = 0; i < 10000; i++)
synchronized(lock) {
x++; x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x always 0!
}
}