This document discusses multi-threaded programming in Java. It covers key concepts like synchronized blocks, static synchronization, deadlocks, inter-thread communication, thread states (new, runnable, running, non-runnable, terminated), creating threads by extending Thread class and implementing Runnable interface, starting threads using start() vs calling run() directly, joining threads, naming threads, setting thread priority, and using methods like sleep(), yield(), currentThread() etc. It provides examples to explain these concepts.
This document discusses exception handling in C++ and Java. It defines what exceptions are and explains that exception handling separates error handling code from normal code to make programs more readable and robust. It covers try/catch blocks, throwing and catching exceptions, and exception hierarchies. Finally, it provides an example of implementing exception handling in a C++ program to handle divide-by-zero errors.
The document discusses exception handling in Java. It explains that exceptions represent runtime errors and can be handled using try, catch, and finally blocks. The key exception types are Exception, RuntimeException, and Error. Exception is the superclass of all exceptions and must be caught, while RuntimeException represents programming errors that do not require catching. Error represents very severe errors outside the program's control. The document provides examples of how to throw, catch, and handle different exception types in Java code.
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
The document discusses various C++ constructors including default constructors, initialization lists, copy constructors, assignment operators, and destructors. It provides examples of how to properly implement these special member functions to avoid problems like shallow copying and double deletes.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that arise during runtime and disrupt normal program flow. There are three types of exceptions: checked exceptions which must be declared, unchecked exceptions which do not need to be declared, and errors which are rare and cannot be recovered from. The try, catch, and finally blocks are used to handle exceptions, with catch blocks handling specific exception types and finally blocks containing cleanup code.
The document summarizes a presentation on exception handling given by the group "Bug Free". It defines what exceptions are, why they occur, and the exception hierarchy. It describes checked and unchecked exceptions, and exception handling terms like try, catch, throw, and finally. It provides examples of using try-catch blocks, multiple catch statements, nested try-catch, and throwing and handling exceptions.
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.
This document discusses polymorphism and inheritance concepts in Java. It defines polymorphism as an object taking on many forms, and describes method overloading and overriding. Method overloading allows classes to have multiple methods with the same name but different parameters. Method overriding allows subclasses to provide a specific implementation of a method in the parent class. The document also discusses abstract classes and interfaces for abstraction in Java, and explains access modifiers like public, private, protected, and default.
The document discusses multithreading and threading concepts in Java. It defines a thread as a single sequential flow of execution within a program. Multithreading allows executing multiple threads simultaneously by sharing the resources of a process. The key benefits of multithreading include proper utilization of resources, decreased maintenance costs, and improved performance of complex applications. Threads have various states like new, runnable, running, blocked, and dead during their lifecycle. The document also explains different threading methods like start(), run(), sleep(), yield(), join(), wait(), notify() etc and synchronization techniques in multithreading.
This document discusses exception handling in C++ and Java. It defines what exceptions are and explains that exception handling separates error handling code from normal code to make programs more readable and robust. It covers try/catch blocks, throwing and catching exceptions, and exception hierarchies. Finally, it provides an example of implementing exception handling in a C++ program to handle divide-by-zero errors.
The document discusses exception handling in Java. It explains that exceptions represent runtime errors and can be handled using try, catch, and finally blocks. The key exception types are Exception, RuntimeException, and Error. Exception is the superclass of all exceptions and must be caught, while RuntimeException represents programming errors that do not require catching. Error represents very severe errors outside the program's control. The document provides examples of how to throw, catch, and handle different exception types in Java code.
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
The document discusses various C++ constructors including default constructors, initialization lists, copy constructors, assignment operators, and destructors. It provides examples of how to properly implement these special member functions to avoid problems like shallow copying and double deletes.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that arise during runtime and disrupt normal program flow. There are three types of exceptions: checked exceptions which must be declared, unchecked exceptions which do not need to be declared, and errors which are rare and cannot be recovered from. The try, catch, and finally blocks are used to handle exceptions, with catch blocks handling specific exception types and finally blocks containing cleanup code.
The document summarizes a presentation on exception handling given by the group "Bug Free". It defines what exceptions are, why they occur, and the exception hierarchy. It describes checked and unchecked exceptions, and exception handling terms like try, catch, throw, and finally. It provides examples of using try-catch blocks, multiple catch statements, nested try-catch, and throwing and handling exceptions.
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.
This document discusses polymorphism and inheritance concepts in Java. It defines polymorphism as an object taking on many forms, and describes method overloading and overriding. Method overloading allows classes to have multiple methods with the same name but different parameters. Method overriding allows subclasses to provide a specific implementation of a method in the parent class. The document also discusses abstract classes and interfaces for abstraction in Java, and explains access modifiers like public, private, protected, and default.
The document discusses multithreading and threading concepts in Java. It defines a thread as a single sequential flow of execution within a program. Multithreading allows executing multiple threads simultaneously by sharing the resources of a process. The key benefits of multithreading include proper utilization of resources, decreased maintenance costs, and improved performance of complex applications. Threads have various states like new, runnable, running, blocked, and dead during their lifecycle. The document also explains different threading methods like start(), run(), sleep(), yield(), join(), wait(), notify() etc and synchronization techniques in multithreading.
The document summarizes different types of Java operators and provides examples of their usage. It discusses arithmetic, relational, logical operators as well as assignment, conditional, and increment/decrement operators. It also covers type conversions in expressions and built-in math functions through the Math class. Examples are provided to demonstrate determining the value of arithmetic, logical expressions and a programming problem on calculating salvage value using straight-line depreciation method.
1. The document discusses threads and multithreading in Java. It defines threads as independent paths of execution within a process and explains how Java supports multithreading.
2. Key concepts covered include the different states a thread can be in (new, ready, running, blocked, dead), thread priorities, synchronization to allow threads to safely access shared resources, and methods to control threads like start(), sleep(), join(), etc.
3. Examples are provided to demonstrate how to create and manage multiple threads that run concurrently and synchronize access to shared resources.
This ppt gives a general idea about the multithreading concepts in the java programming language. hope you find it useful
P.S :
sorry there is a correction in one of the slides
where i have entered implements thread
it is wrong it is actually implements Runnable
thank you!
Polymorphism in Java allows an object to take on multiple forms. There are two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Method overloading involves methods with the same name but different parameters, while method overriding involves subclasses providing their own implementation of a superclass method. Runtime polymorphism determines which version of a method to call based on the object's actual type at runtime. Abstraction in Java allows hiding implementation details and showing only essential functionality through the use of abstract classes and methods.
This document discusses arrays in Java programming. It covers defining and creating single and multi-dimensional arrays, accessing array elements using indexes and loops, and performing operations like sorting and finding maximum/minimum values. Examples are provided for different array types like integer, string and character arrays, and operations like input/output, break/continue statements, and star patterns. Homework involves writing a program to produce a given output pattern.
This document discusses inheritance in object-oriented programming. It defines inheritance as establishing a link between classes that allows sharing and accessing properties. There are three types of inheritance: single, multilevel, and hierarchical. Single inheritance involves one parent and one child class, multilevel inheritance adds intermediate classes, and hierarchical inheritance has one parent and multiple child classes. The document provides examples of inheritance code in Java and demonstrates a program using inheritance with interfaces. It notes some limitations of inheritance in Java.
The ArrayList class provides a resizable array implementation of the List interface. It allows for adding and removing elements dynamically and permits null values. The ArrayList has low constant overhead compared to LinkedList. It implements all optional list operations. Methods like add(), get(), set(), remove(), clear(), and size() can be used to manipulate elements.
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.
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
The document discusses String handling in Java. It describes how Strings are implemented as objects in Java rather than character arrays. It also summarizes various methods available in the String and StringBuffer classes for string concatenation, character extraction, comparison, modification, and value conversion. These methods allow extracting characters, comparing strings, modifying strings, and converting between string and other data types.
This document discusses the java.util.StringTokenizer class which allows breaking a string into tokens. It describes the constructors and methods of StringTokenizer, including how to count, check for, and retrieve the next token. An example program demonstrates its use by tokenizing a sample string and outputting the results.
Method overriding allows a subclass to provide a specific implementation of a method that is already provided by its superclass. The subclass method must have the same name, parameters and return type as the superclass method. This allows the subclass to modify the behavior as needed and is how polymorphism is implemented. The super keyword can be used to call the superclass method from the overriding method.
The document discusses inheritance in C++. It defines inheritance as deriving a class from another class, allowing code reuse and fast development. There are different types of inheritance in C++: single inheritance where a class inherits from one base class; multiple inheritance where a class inherits from more than one base class; multilevel inheritance where a derived class inherits from another derived class; hierarchical inheritance where multiple subclasses inherit from a single base class; and hybrid inheritance which combines different inheritance types. Examples of each inheritance type are provided in C++ code snippets.
The document discusses various looping constructs in Java including for, while, do-while loops as well as decision making statements like if, if-else, switch. It provides the syntax and examples of each. The key loops covered are for, which allows looping a specific number of times, while which checks a condition before running the loop body, and do-while which runs the body at least once. The document also discusses break and continue keywords that can be used within loops. For decision making, it explains if, if-else-if-else for multiple conditions, and switch for equality checks. Nested if statements are also covered.
This document discusses exception handling in Java. It defines exceptions as events that disrupt normal program flow. It describes try/catch blocks for handling exceptions and lists advantages like separating error handling code. It discusses different exception types like checked exceptions that must be declared, unchecked exceptions for logic errors, and Errors for JVM problems. It provides best practices like throwing exceptions for broken contracts and guidelines for when to catch exceptions. It also describes antipatterns to avoid, like catching generic exceptions, and exception logging and chaining techniques.
In this core java training session, you will learn Collections. Topics covered in this session are:
• Recap of Arrays
• Introduction to Collections API
• Lists – ArrayList, Vector, LinkedList
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
The document discusses exception handling in Java. It describes different types of errors like compile-time errors and run-time errors. It explains checked and unchecked exceptions in Java. Checked exceptions must be handled, while unchecked exceptions may or may not be handled. Finally, it covers how to create user-defined exceptions in Java by extending the Exception class and throwing exceptions using the throw keyword.
This document discusses inter-thread communication methods like wait() and notify() that allow threads to synchronize access to shared resources. It describes the producer-consumer problem that can occur when threads access a shared buffer without synchronization. It provides examples of incorrect and correct implementations of the producer-consumer pattern using wait(), notify(), and synchronization to allow a producer thread to add items to a buffer while a consumer thread removes items.
The document discusses best practices for API design. It covers topics such as considering the perspective of the caller, keeping APIs simple, striving for consistency, choosing memorable names, specifying behavior, making APIs safe, anticipating evolution, and writing helpful documentation. The overall message is that API design has a significant impact and requires careful consideration to create interfaces that are intuitive, easy to use, and stand the test of time.
The document summarizes different types of Java operators and provides examples of their usage. It discusses arithmetic, relational, logical operators as well as assignment, conditional, and increment/decrement operators. It also covers type conversions in expressions and built-in math functions through the Math class. Examples are provided to demonstrate determining the value of arithmetic, logical expressions and a programming problem on calculating salvage value using straight-line depreciation method.
1. The document discusses threads and multithreading in Java. It defines threads as independent paths of execution within a process and explains how Java supports multithreading.
2. Key concepts covered include the different states a thread can be in (new, ready, running, blocked, dead), thread priorities, synchronization to allow threads to safely access shared resources, and methods to control threads like start(), sleep(), join(), etc.
3. Examples are provided to demonstrate how to create and manage multiple threads that run concurrently and synchronize access to shared resources.
This ppt gives a general idea about the multithreading concepts in the java programming language. hope you find it useful
P.S :
sorry there is a correction in one of the slides
where i have entered implements thread
it is wrong it is actually implements Runnable
thank you!
Polymorphism in Java allows an object to take on multiple forms. There are two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Method overloading involves methods with the same name but different parameters, while method overriding involves subclasses providing their own implementation of a superclass method. Runtime polymorphism determines which version of a method to call based on the object's actual type at runtime. Abstraction in Java allows hiding implementation details and showing only essential functionality through the use of abstract classes and methods.
This document discusses arrays in Java programming. It covers defining and creating single and multi-dimensional arrays, accessing array elements using indexes and loops, and performing operations like sorting and finding maximum/minimum values. Examples are provided for different array types like integer, string and character arrays, and operations like input/output, break/continue statements, and star patterns. Homework involves writing a program to produce a given output pattern.
This document discusses inheritance in object-oriented programming. It defines inheritance as establishing a link between classes that allows sharing and accessing properties. There are three types of inheritance: single, multilevel, and hierarchical. Single inheritance involves one parent and one child class, multilevel inheritance adds intermediate classes, and hierarchical inheritance has one parent and multiple child classes. The document provides examples of inheritance code in Java and demonstrates a program using inheritance with interfaces. It notes some limitations of inheritance in Java.
The ArrayList class provides a resizable array implementation of the List interface. It allows for adding and removing elements dynamically and permits null values. The ArrayList has low constant overhead compared to LinkedList. It implements all optional list operations. Methods like add(), get(), set(), remove(), clear(), and size() can be used to manipulate elements.
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.
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
The document discusses String handling in Java. It describes how Strings are implemented as objects in Java rather than character arrays. It also summarizes various methods available in the String and StringBuffer classes for string concatenation, character extraction, comparison, modification, and value conversion. These methods allow extracting characters, comparing strings, modifying strings, and converting between string and other data types.
This document discusses the java.util.StringTokenizer class which allows breaking a string into tokens. It describes the constructors and methods of StringTokenizer, including how to count, check for, and retrieve the next token. An example program demonstrates its use by tokenizing a sample string and outputting the results.
Method overriding allows a subclass to provide a specific implementation of a method that is already provided by its superclass. The subclass method must have the same name, parameters and return type as the superclass method. This allows the subclass to modify the behavior as needed and is how polymorphism is implemented. The super keyword can be used to call the superclass method from the overriding method.
The document discusses inheritance in C++. It defines inheritance as deriving a class from another class, allowing code reuse and fast development. There are different types of inheritance in C++: single inheritance where a class inherits from one base class; multiple inheritance where a class inherits from more than one base class; multilevel inheritance where a derived class inherits from another derived class; hierarchical inheritance where multiple subclasses inherit from a single base class; and hybrid inheritance which combines different inheritance types. Examples of each inheritance type are provided in C++ code snippets.
The document discusses various looping constructs in Java including for, while, do-while loops as well as decision making statements like if, if-else, switch. It provides the syntax and examples of each. The key loops covered are for, which allows looping a specific number of times, while which checks a condition before running the loop body, and do-while which runs the body at least once. The document also discusses break and continue keywords that can be used within loops. For decision making, it explains if, if-else-if-else for multiple conditions, and switch for equality checks. Nested if statements are also covered.
This document discusses exception handling in Java. It defines exceptions as events that disrupt normal program flow. It describes try/catch blocks for handling exceptions and lists advantages like separating error handling code. It discusses different exception types like checked exceptions that must be declared, unchecked exceptions for logic errors, and Errors for JVM problems. It provides best practices like throwing exceptions for broken contracts and guidelines for when to catch exceptions. It also describes antipatterns to avoid, like catching generic exceptions, and exception logging and chaining techniques.
In this core java training session, you will learn Collections. Topics covered in this session are:
• Recap of Arrays
• Introduction to Collections API
• Lists – ArrayList, Vector, LinkedList
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
The document discusses exception handling in Java. It describes different types of errors like compile-time errors and run-time errors. It explains checked and unchecked exceptions in Java. Checked exceptions must be handled, while unchecked exceptions may or may not be handled. Finally, it covers how to create user-defined exceptions in Java by extending the Exception class and throwing exceptions using the throw keyword.
This document discusses inter-thread communication methods like wait() and notify() that allow threads to synchronize access to shared resources. It describes the producer-consumer problem that can occur when threads access a shared buffer without synchronization. It provides examples of incorrect and correct implementations of the producer-consumer pattern using wait(), notify(), and synchronization to allow a producer thread to add items to a buffer while a consumer thread removes items.
The document discusses best practices for API design. It covers topics such as considering the perspective of the caller, keeping APIs simple, striving for consistency, choosing memorable names, specifying behavior, making APIs safe, anticipating evolution, and writing helpful documentation. The overall message is that API design has a significant impact and requires careful consideration to create interfaces that are intuitive, easy to use, and stand the test of time.
This document discusses concurrency and concurrent programming in Java. It introduces the built-in concurrency primitives like wait(), notify(), synchronized, and volatile. It then discusses higher-level concurrency utilities and data structures introduced in JDK 5.0 like Executors, ExecutorService, ThreadPools, Future, Callable, ConcurrentHashMap, CopyOnWriteArrayList that provide safer and more usable concurrency constructs. It also briefly covers topics like Java Memory Model, memory barriers, and happens-before ordering.
This document discusses alternate concurrency models including the actor model and software transactional memory (STM). It provides overviews of common problems with multi-threading like atomicity, visibility and race conditions. The actor model is described as involving autonomous units that communicate asynchronously via message passing without shared state. STM is analogous to database transactions for controlling concurrency in shared memory through atomic reads and writes. Examples of actor model applications and STM implementations in Java are also mentioned.
This document introduces multi-threading in Java. It discusses that threads allow a program to have multiple paths of execution. Threads can be created by extending the Thread class or implementing the Runnable interface. The key method for threads is run, which contains the logic to be executed. The document covers starting threads, potential problems with threads accessing shared resources, and techniques for thread synchronization like synchronized methods, waits and notifies.
The document provides guidelines for various naming conventions including:
- Standards for naming variables, member functions, local variables, and method arguments.
- Standards for naming classes, interfaces and packages.
- Guidelines related to code documentation, comments and indentation.
- Common coding errors and best practices to avoid them.
Based on your responses, here are a few things you can focus on to better nail the interview:
- Practice answering common questions like "Tell me about yourself" so you have clear, concise responses prepared. Have specific examples from your background to draw from.
- Research the company and position thoroughly so you understand what skills and experience they are looking for. Connect your background to their needs.
- Anticipate questions that may be asked and have well-thought out, positive responses prepared. Practice your delivery.
- Ask insightful questions yourself to demonstrate your interest and qualifications for the role. Follow up after the interview as well.
Preparing thoroughly, anticipating questions, connecting your background to their needs
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
Life as a software engineer is so exciting! Computing power continue to rise exponentially, software demands continue to rise exponentially as well, so far so good. The bad news are that in the last decade the computing power of single threaded application remains almost flat.
If you decide to continue ignoring concurrency and multi-threading the gap between the problems you are able to solve and your hardware capabilities will continue to rise. In this session we will discuss different approaches for taming the concurrency beast, such as shared mutability,shared immutability and isolated mutability actors, STM, etc we will discuss the shortcomings and the dangers of each approach and we will compare different programming languages and how they choose to tackle/ignore concurrency.
The document discusses inner classes, static classes, and multithreading in Java. It defines inner classes as classes defined within other classes. There are four types of inner classes: non-static, static, local, and anonymous. Static inner classes are similar to top-level classes but are declared within another class. They can be accessed without creating an instance of the outer class. Multithreading allows multiple parts of a program to run concurrently by using threads.
The document discusses different types of linked lists including singly linked lists, doubly linked lists, and circularly linked lists. Singly linked lists contain nodes that point to the next node in the list, while doubly linked lists contain nodes that point to both the next and previous nodes. Circularly linked lists form a circle with the last node pointing back to the first node. The document provides code examples for common linked list operations like insertion, removal and traversal for each of the linked list types.
The document discusses Java I/O streams and input/output. It introduces streams as an ordered sequence of data linked to a physical device. Streams can represent different sources and destinations like files, devices, networks. Input streams read data from a source while output streams write data to a destination. Byte streams handle bytes and character streams handle characters. Important stream classes include InputStream, OutputStream, Reader, and Writer. The System class defines predefined input, output, and error streams. Reading input involves wrapping System.in in a BufferedReader while writing uses PrintStream.
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
Designed for the beginning Java developer to grasp advanced Java multi-threading concepts quickly. Talks mainly about the Java Memory Model and the Concurrent Utilities. This presentation is Java-specific and we intentionally omit general non-Java-specific details, such as hardware architecture, OS, native threads, algorithms, and general software design principles etc.
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.
The document discusses recursion, including:
1) Recursion involves breaking a problem down into smaller subproblems until a base case is reached, then building up the solution to the overall problem from the solutions to the subproblems.
2) A recursive function is one that calls itself, with each call typically moving closer to a base case where the problem can be solved without recursion.
3) Recursion can be linear, involving one recursive call, or binary, involving two recursive calls to solve similar subproblems.
The document provides an overview of multi-threading in Java. It discusses key concepts like processes vs threads, the thread life cycle, and how to create threads using the Runnable interface and Thread class. It also covers thread synchronization and inter-thread communication. The document is presented by Ravi Kant Sahu, an assistant professor at Lovely Professional University in Punjab, India.
Presentation describes basic concepts of thread pool such as:
- interacting with queues,
- using pools from Executors class,
- task rejecting
- using ThreadFactory for thread creating
- Future and Callable interfaces,
- basic API
- possibilities for extending
What are the top 10 Java Interview Questions and Answers in 2014? Based on the most popular java questions asked in interview, we've compiled a list of the 10 most popular java interview questions in 2014.
Appearing for a java interview is not easy but if you brush up enough fundamentals, then you can easily crack the interview. The above questions are the most popular java interview questions asked by major companies so make sure to download this pdf.
This list includes java interview questions in the below categories:
top 10 java interview questions
top 10 java interview questions and answers
10 most popular interview questions
core java interview questions and answers
basic java interview questions and answers
serialization in java interview questions
core java interview questions pdf
multithreading in java interview questions
advanced java interview questions and answers
top 10 java interview questions and answers for freshers
top 100 java interview questions and answers
java interview questions and answers pdf
java interview questions and answers for freshers
java interview questions and answers for experienced
java interview questions and answers for 3 years experience
java interview questions and answers pdf download
java collections interview questions and answers
The document discusses process synchronization and deadlocks. It introduces race conditions, critical sections, and solutions to synchronize processes like semaphores. Classical problems like the dining philosophers problem and bridge crossing example are presented. Deadlocks are characterized by conditions like mutual exclusion, hold and wait, no preemption and circular wait. Methods to handle deadlocks include prevention through ordering of resource requests and avoidance using resource allocation states.
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. It runs on a variety of platforms such as Windows, Mac OS, and various versions of UNIX. Key features of Java include being object-oriented, platform independent, robust, interpreted, and multi-threaded. When Java is compiled, it is compiled into platform independent byte code that is distributed and interpreted by the Java Virtual Machine (JVM) on whichever platform it is being run on, providing platform independence. Common Java IDEs include Netbeans and Eclipse.
This document contains questions and answers related to Java programming. It has multiple chapters on Java concepts like data types, operators, control statements, classes, inheritance and exception handling. Each chapter contains multiple questions asking to write Java programs demonstrating the related concept. The questions range from very basic programs printing strings to more complex programs using classes, objects, inheritance and exceptions.
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
Multithreading in Java allows executing multiple threads simultaneously. A thread is the smallest unit of processing and is lightweight. Threads share memory space, which saves memory compared to processes that have separate memory areas. Context switching between threads is also faster than between processes. Common uses of multithreading include games, animations, and performing multiple operations simultaneously to save time while individual threads remain independent and unaffected by exceptions in other threads.
- The document discusses multithreading concepts in Java like thread life cycle, creating threads, thread synchronization, and inter-thread communication.
- It explains that threads are lightweight subprocesses that share memory space for better efficiency compared to processes. Threads can run concurrently to achieve multitasking.
- The key methods for working with threads are discussed including start(), sleep(), join(), getName(), setName() and currentThread().
Threads : Single and Multitasking, Creating and terminating the thread, Single and Multi tasking
using threads, Deadlock of threads, Thread communication.
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.
Multithreading in Java allows executing multiple threads simultaneously by using lightweight subprocesses called threads that can perform tasks in parallel. Threads share the same memory area, making context switching faster than multiprocessing. This allows tasks to be performed together, improving performance over single-threaded processes. Common uses of multithreading include games, animations, and achieving responsiveness in applications.
Multithreading allows a program to split into multiple subprograms called threads that can run concurrently. Threads go through various states like new, runnable, running, blocked, and dead. There are two main ways to create threads: by extending the Thread class or implementing the Runnable interface. Threads can have different priorities that influence scheduling order. Multithreading allows performing multiple operations simultaneously to save time without blocking the user, and exceptions in one thread do not affect others.
The document discusses multithreading in Java. It defines multithreading as executing multiple threads simultaneously, with threads being lightweight subprocesses that share a common memory area. This allows multitasking to be achieved more efficiently than with multiprocessing. The advantages of multithreading include not blocking the user, performing operations together to save time, and exceptions in one thread not affecting others. The document also covers thread states, creating and starting threads, and common thread methods.
This document provides an introduction to multithreading in Java. It discusses that a thread is similar to a program with a single flow of control and Java supports executing multiple threads concurrently through multithreading. It describes the different states a thread passes through during its lifetime, including newborn, runnable, running, blocked, and dead. It also explains how to create threads in Java by extending the Thread class or implementing the Runnable interface and calling the start() method. Finally, it discusses synchronization which is used to prevent threads from concurrently accessing shared resources and introduces race conditions.
The document discusses threads and multithreading in Java. It defines a thread as a single sequential flow of control within a program. Multithreading allows a program to be divided into multiple subprograms that can run concurrently. Threads have various states like newborn, runnable, running, blocked, and dead. The key methods for managing threads include start(), sleep(), yield(), join(), wait(), notify(). Synchronization is needed when multiple threads access shared resources to prevent inconsistencies. Deadlocks can occur when threads wait indefinitely for each other.
Threads allow multiple tasks to run concurrently within a single process. Each thread has its own call stack and shares resources like memory with other threads in the same process. There are two main ways to implement threads in Java - by extending the Thread class or implementing the Runnable interface. Synchronization is needed when multiple threads access shared resources to prevent data corruption. Common methods like start(), join(), sleep() and priority help control thread execution and behavior.
This document provides information about Java threads through a series of slides. It defines a thread as a single sequential flow of control within a program. It discusses how to define and launch threads by extending the Thread class or implementing the Runnable interface. It outlines the life cycle of a thread and its possible states such as new, runnable, blocked, waiting and terminated. It also covers how to interrupt threads and related methods.
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 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.
The document discusses various aspects of threads in Java such as the join method, which allows one thread to wait for another to finish executing; setting thread priorities and daemon status; using thread pools for better performance; and shutdown hooks, which allow code to run when the JVM shuts down. It also covers thread groups for managing multiple threads and risks associated with thread pools such as deadlocks if tasks wait on each other.
Multithreading in Java allows executing multiple threads simultaneously. A thread is the smallest unit of processing and threads are lightweight sub-processes that are independent. If an exception occurs in one thread, it does not affect other threads. There are five states in the lifecycle of a thread: new, runnable, running, non-runnable (blocked), and terminated. Threads can be created by extending the Thread class or implementing the Runnable interface.
- Threads are lightweight processes that can be executed concurrently within a process to improve responsiveness and resource utilization.
- Threads share the same memory as the process they belong to, making communication between threads cheaper than between processes.
- The main() method represents the initial thread when a Java program starts. Additional threads can be created by extending the Thread class or implementing the Runnable interface.
1) Arrays allow storing multiple values of the same type under one variable name using subscripts. One-dimensional arrays store elements in a single list, while multi-dimensional arrays can store elements in multiple lists.
2) Control statements like if/else, switch, while, do-while, for, break, continue and return allow altering the flow of execution in a program.
3) Classes are blueprints that define the structure and behavior of objects. Classes contain variables and methods, and objects are instances of classes that store their own set of variable values.
This document discusses Java packages and interfaces. It covers topics like:
- Packages are used to group related classes and interfaces and provide benefits like reuse and separation of design from code.
- Well-known Java API packages include java.lang, java.util, java.io, java.awt, and java.net.
- There are two ways to access classes from packages: using fully qualified names or import statements.
- Interfaces are used for multiple inheritance in Java and define abstract methods that implementing classes must define. Interfaces can extend other interfaces.
1. The document discusses various Java programming concepts like methods, classes, inheritance, method overloading, recursion, access modifiers, static, final, abstract etc.
2. It provides examples to explain method overloading, constructor overloading, recursion, inheritance forms like single, multilevel, hierarchical etc.
3. It also discusses the usage of keywords like final, static, abstract and usage of super keyword in inheritance.
The document discusses various techniques for memory management in computer systems. It covers the following key points:
- Computer memory is made up of cells that can exist in two states corresponding to bit values. Memory can use different physical properties like electrical charge or magnetism.
- Memory is either volatile, requiring constant power, or non-volatile like hard disks that retain data without power.
- Operating systems use memory management to handle RAM and map logical to physical addresses. Techniques include paging, segmentation, and virtual memory address translation with page tables.
- Memory management aims to utilize memory efficiently and protect processes from one another through allocation schemes, relocation of code, and partitioning of physical memory.
The document discusses virtual memory concepts including demand paging, page replacement algorithms, and allocation of memory frames. Demand paging brings pages into memory only when needed, reducing I/O and memory usage. When a page fault occurs and there is no free frame, page replacement algorithms like FIFO, LRU, and second chance are used to select a page to remove from memory. Frames can be allocated to processes using fixed or priority schemes.
Control statements allow programs to select different execution paths based on conditions or iterate through loops. Common control statements in Java include if/else for conditional branching, while, do-while and for for iterative loops, and break, continue, return for jumping execution.
Classes are templates that define the form and behavior of objects. A class contains instance variables to represent object state and methods to implement object behavior. Objects are instances of classes that allocate memory at runtime. Methods allow classes to encapsulate and reuse code. Constructors initialize new objects and this keyword refers to the current object instance. Garbage collection automatically reclaims unused memory from objects no longer referenced.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
4. G
Multi -threading
in
Java
Multithreading in java is a process of
executing multiple threads simultaneously.
But we use multithreading than
multiprocessing because threads share a
common memory area. They don't allocate
separate memory area so saves memory, and
context-switching between the threads takes
less time than process.
Java Multithreading is mostly used in games,
animation etc.
5. G
Advantage
of
Java
Multi
threading
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.
6. G
Multitasking is a process of executing
multiple tasks simultaneously.
We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Multi
tasking
7. G
Process-based Multitasking (Multiprocessing)
Each process have its own address in
memory i.e. each process allocates separate
memory area.
Process is heavyweight.
Cost of communication between the process
is high.
Switching from one process to another
require some time for saving and loading
registers, memory maps, updating lists etc.
Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread
is low.
Multi
tasking
8. G
A thread is a lightweight sub process, a
smallest unit of processing. It is a separate
path of execution.
Threads are independent, if there occurs
exception in one thread, it doesn't affect other
threads. It shares a common memory area.
What
is Thread in
java?
t2
t1t3
process1
process2
process3
OS
Thread is executed ins
process. There is context
switching between the t
There can be multiple
processes inside the OS a
one process can have mu
threads.
Note: At a time one th
executed only.
9. G
Life cycle of a
Thread
(Thread States)
A thread can be in one of the five states.
According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-
runnable and terminated. There is no running
state.
But for better understanding the threads, we
are explaining it in the 5 states.
The life cycle of the thread in java is
controlled by JVM. The java thread states are
as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated(Dead)
10. G
Life cycle of a
Thread
(Thread States)
New
Runnable
Running
terminated
Non -
Runnable
Start()
run() method
exists
Sleep , block on I/O , wait
for lock , suspend , wait
Sleep done, I/O completer, lock
available , resume, notify
11. G
1) New
The thread is in new state if you create an
instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation
of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
The thread is in running state if the thread
scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive,
but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when
its run() method exits.
Life cycle of a
Thread
(Thread States)
12. G
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface
How to create
thread
Thread class Thread class provide constructors and
methods to create and perform operations on
a thread .
Thread class extends Object class and
implements Runnable interface.
Commonly
used
Constructors of
Thread class
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
13. public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
14. G
Runnable
interface
The Runnable interface should be
implemented by any class whose instances are
intended to be executed by a thread.
Runnable interface have only one method
named run().
public void run(): is used to perform action
for a thread
Starting a
thread
start() method of Thread class is used to start
a newly created thread.
It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the
Runnable state.
When the thread gets a chance to execute,
its target run() method will run.
15. G
By extending
Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output :
thread is running...
Who makes your
class object as
thread object?
Thread class constructor allocates a new
thread object.
When you create object of Multi class , your
class constructor is invoked(provided by
Compiler) from where Thread class constructor
is invoked(by super() as first statement).
So your Multi class object is thread object
now.
16. G
By implementing
the Runnable
interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output :
thread is running...
If you are not extending the Thread class , your
class object would not be treated as a thread
object . So you need to explicitely create
Thread class object.We are passing the object
of your class that implements Runnable so that
your class run() method may execute.
17. G
Thread Scheduler
in Java
Thread scheduler in java is the part of the JVM
that decides which thread should run.
There is no guarantee that which runnable
thread will be chosen to run by the thread
scheduler.
Only one thread at a time can run in a single
process.
The thread scheduler mainly uses preemptive
or time slicing scheduling to schedule the
threads.
Under preemptive scheduling, the highest
priority task executes until it enters the waiting
or dead states or a higher priority task comes
into existence. Under time slicing, a task
executes for a predefined slice of time and
then reenters the pool of ready tasks. The
scheduler then determines which task should
execute next, based on priority and other
factors.
Difference between
preemptive
scheduling and time
slicing
18. G
Sleep method
in java
The sleep() method of Thread class is used to
sleep a thread for the specified amount of
time.
The Thread class provides two methods for
sleeping a thread:
public static void sleep(long
miliseconds)throws InterruptedException
public static void sleep(long miliseconds, int
nanos)throws InterruptedException
Syntax
of
sleep() method
in java
19. G
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);
}
catch(InterruptedException e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod
1();
TestSleepMethod1 t2=new TestSleepMethod
1();
t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
As you know well th
at a time only one
thread is executed. I
you sleep a thread fo
the specified time , t
thread scheduler pic
up another thread a
so on.
Example of sleep
method in java
20. G
Can we start a
thread twice
No. After starting a thread, it can never be
started again. If you does so, an
IllegalThreadStateException is thrown. In such
case, thread will run once but for second time,
it will throw exception
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1(
);
t1.start();
t1.start();
}
}
Output :
running …
Exception in thread
"main"
java.lang.IllegalThre
StateException
21. G
What if we call
run() method
directly instead
start() method?
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.
class TestCallRun1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate c
all stack
}
}
22. G
class TestCallRun2 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);}catch(InterruptedException
e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}
Output:
1
2
3
4
5
1
2
3
4
5
Problem if you
direct call run()
method
23. G
The join()
method
The join() method waits for a thread to die.
In other words, it causes the currently
running threads to stop executing until the
thread it joins with completes its task.
Syntax
public void join()throws InterruptedException
public void join(long milliseconds)throws
InterruptedException
24. G
Example of
join() method
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above
example,when t1 completes its task
then t2 and t3 starts executing
25. G
class TestJoinMethod2 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:
1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the above example,when t1 is
completes its task for 1500
miliseconds(3 times) then t2 and t3
starts executing
Example
Of
join(long
miliseconds) method
26. G
getName(),
setName(String)
and getId()
method
public String getName()
public void setName(String name)
public long getId()
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:
Name of t1:Thread
Name of t2:Thread
id of t1:8
running...
After changling nam
running...
27. G
The Thread class provides methods to change
and get the name of a thread.public String
getName(): is used to return the name of a
thread.
public void setName(String name): is used to
change the name of a thread.
Naming
a thread
28. G
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1
();
TestMultiNaming1 t2=new TestMultiNaming1
();
System.out.println("Name of t1:"+t1.getNam
e());
System.out.println("Name of t2:"+t2.getNam
e());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t
1:"+t1.getName());
}
}
Output:
Name of t1:Thread
Name of t2:Thread
id of t1:8
running...
After changeling na
running...
Example of
naming a
thread
29. G
The
currentThrea
d() method
The currentThread() method returns a
reference to the currently executing thread
object
Syntax of currentThread() method:
• public static Thread
currentThread(): returns the reference of
currently running thread
30. G
class TestMultiNaming2 extends Thread{
public void run(){
System.out.println(Thread.currentThread().ge
tName());
}
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2
();
TestMultiNaming2 t2=new TestMultiNaming2
();
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
Example of
currentThread(
) method
31. G
Priority of a
Thread (Thread
Priority)
Each thread have a priority. Priorities are
represented by a number between 1 and 10. In
most cases, thread schedular schedules the
threads according to their priority (known as
preemptive scheduling). But it is not
guaranteed because it depends on JVM
specification that which scheduling it chooses
3 constants defienEd in Thread class
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
Default priority of a thread is 5
(NORM_PRIORITY). The value of MIN_PRIORITY is
1 and the value of MAX_PRIORITY is 10
32. G
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"
+Thread.currentThread().getName());
System.out.println("running thread priority is
:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1
();
TestMultiPriority1 m2=new TestMultiPriority1
();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Example of
priority of a
Thread
Output:
running thread nam
running thread prior
running thread nam
running thread prior
33. G
Daemon
Thread in Java
Daemon thread in java is a service provider
thread that provides services to the user
thread. Its life depend on the mercy of user
threads i.e. when all the user threads dies,
JVM terminates this thread automatically.
There are many java daemon threads running
automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole
in the command prompt. The jconsole tool
provides information about the loaded classes,
memory usage, running threads etc.
Points to remember for Daemon Thread in Java
It provides services to user threads for
background supporting tasks. It has no role in
life than to serve user threads.
Its life depends on user threads.
It is a low priority thread.
34. G
The sole purpose of the daemon thread is that
it provides services to user thread for
background supporting task. If there is no user
thread, why should JVM keep running this
thread. That is why JVM terminates the
daemon thread if there is no user thread.
Why JVM
terminates the
daemon thread if
there is no user
thread?
No. Method Description
1) public void
setDaemon(boo
lean status)
is used to
mark the
current thread
as daemon
thread or user
thread.
2) public boolean
isDaemon()
is used to
check that
current is
daemon.
Methods for Java
Daemon thread
by Thread class
35. G
Simple example
of Daemon
thread in java
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon())
{//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();
//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work user
thread work
Note: If you want
to make a user
thread as
Daemon, it must
not be started
otherwise it will
throw
IllegalThreadStat
eException.
36. G
class TestDaemonThread2 extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentT
hread().getName());
System.out.println("Daemon: "+Thread.curre
ntThread().isDaemon());
}
public static void main(String[] args){
TestDaemonThread2 t1=new TestDaemonThr
ead2();
TestDaemonThread2 t2=new TestDaemonThr
ead2();
t1.start();
t1.setDaemon(true);//will throw exception he
re
t2.start();
}
}
Output:
exception in thread
main:java.lang.Illegal
ThreadStateException
37. G
Java Thread pool represents a group of
worker threads that are waiting for the job and
reuse many times.
In case of thread pool, a group of fixed size
threads are created. A thread from the thread
pool is pulled out and assigned a job by the
service provider. After completion of the job,
thread is contained in the thread pool again.Java
Thread
Pool
Advantage of Java Thread Pool
Better performance It saves time because
there is no need to create new thread.
Real time usage
It is used in Servlet and JSP where container
creates a thread pool to process the request.
38. import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getN
ame()+" (Start) message = "+message);
processmessage();
System.out.println(Thread.currentThread().getN
ame()+" (End)");
}
private void processmessage() {
try { Thread.sleep(2000); } catch
(InterruptedException e) { e.printStackTrace(); }
}
}
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor =
Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread(""
+ i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
40. G
In a network server program, one thread waits
for and accepts requests from client programs
to execute, for example, database transactions
or complex calculations. The thread usually
creates a new thread to handle the request.
Depending on the request volume, many
different threads might be simultaneously
present, complicating thread management. To
simplify thread management, programs
organize their threads with thread groups—
java.lang.ThreadGroup objects that group
related threads' Thread (and Thread subclass)
objects. For example, your program can use
ThreadGroup to group all printing threads into
one group
Thread groups
41. G
class ThreadGroupDemo
{
public static void main (String [] args)
{
ThreadGroup tg = new ThreadGroup
("subgroup 1");
Thread t1 = new Thread (tg, "thread 1");
Thread t2 = new Thread (tg, "thread 2");
Thread t3 = new Thread (tg, "thread 3");
tg = new ThreadGroup ("subgroup 2");
Thread t4 = new Thread (tg, "my thread");
tg = Thread.currentThread
().getThreadGroup ();
int agc = tg.activeGroupCount ();
System.out.println ("Active thread groups
in " + tg.getName () +
" thread group: " + agc);
tg.list ();
}
}
Active thread groups
in main thread
group: 2
java.lang.ThreadGrou
p[name=main,maxpr
i=10]
Thread[main,5,main]
java.lang.ThreadGrou
p[name=subgroup
1,maxpri=10]
java.lang.ThreadGrou
p[name=subgroup
2,maxpri=10]
example
of
thread
group
in java
42. G
ThreadGroups can contain not only
threads but also other ThreadGroups.
The top-most thread group in a Java
application is the thread group named
main.
You can create threads and thread
groups in the main group.
You can also create threads and
thread groups in subgroups of main.
The result is a root-like hierarchy of
threads and thread groups:
The
ThreadGroup
Class
43. G
Methods that
Operate on the
Group
The ThreadGroup class supports several
attributes that are set and retrieved from the
group as a whole. These attributes include the
maximum priority that any thread within the
group can have, whether the group is a
"daemon" group, the name of the group, and
the parent of the group.
The methods that get and set ThreadGroup
attributes operate at the group level. They
inspect or change the attribute on the
ThreadGroup object, but do not affect any of
the threads within the group. The following is
a list of ThreadGroup methods that operate at
the group level:
getMaxPriority and setMaxPriority
getDaemon and setDaemon
getName
getParent and parentOf
toString
44. G
The ThreadGroup class has three
methods that allow you to modify the
current state of all the threads within that
group:
resume
stop
suspend
These methods apply the appropriate
state change to every thread in the thread
group and its subgroups.
Methods that
Operate on All
Threads within
a Group
45. G
The ThreadGroup class itself does not impose
any access restrictions, such as allowing threads
from one group to inspect or modify threads in a
different group. Rather the Thread and
ThreadGroup classes cooperate with security
managers (subclasses of the SecurityManager
class), which can impose access restrictions
based on thread group membership
The following is a list of ThreadGroup methods
that call ThreadGroup's checkAccess before
performing the action of the method. These are
what are known as regulated accesses, that is,
accesses that must be approved by the security
manager before they can be completed.
ThreadGroup(ThreadGroup parent, String name)
setDaemon(boolean isDaemon)
setMaxPriority(int maxPriority)
stop
suspend
resume
destroy
Access Restriction
Methods
46. G
Shutdown Hook
The shutdown hook can be used to perform
cleanup resource or save the state when JVM
shuts down normally or abruptly. Performing
clean resource means closing log file, sending
some alerts or something else. So if you want to
execute some code before JVM shuts down, use
shutdown hook.
When does the JVM shut down?
The JVM shuts down when:
•user presses ctrl+c on the command prompt
•System.exit(int) method is invoked
•user logoff
•user shutdown etc.
The addShutdownHook(Runnable r) method
The addShutdownHook() method of Runtime
class is used to register the thread with the
Virtual Machine. Syntax:
public void addShutdownHook(Runnable r){}
The object of Runtime class can be obtained by
calling the static factory method getRuntime().
For example:
Runtime r = Runtime.getRuntime();
47. G
Simple example of
Shutdown Hook
class MyThread extends Thread{
public void run(){
System.out.println("shut down hook task c
ompleted..");
}
}
public class TestShutdown1{
public static void main(String[] args)throws Exc
eption {
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread());
System.out.println("Now main sleeping... press
ctrl+c to exit");
try{Thread.sleep(3000);}catch (Exception e) {}
}
}
Output:
Now main
sleeping... press
ctrl+c to exit
shut down hook
task completed..
Note: The
shutdown
sequence can
be stopped by
invoking the
halt(int)
method of
Runtime class.
48. G
Java Runtime class is used to interact with java
runtime environment. Java Runtime class
provides methods to execute a process, invoke
GC, get total and free memory etc. There is
only one instance of java.lang.Runtime class is
available for one java application.
The Runtime.getRuntime() method returns
the singleton instance of Runtime class
Java Runtime
class
Method Description
public static Runtime
getRuntime()
returns the instance of Runtime
class.
public void exit(int status)
terminates the current virtual
machine.
public void
addShutdownHook(Thread hook)
registers new hook thread.
public Process exec(String
command)throws IOException
executes given command in a
separate process.
public int availableProcessors()
returns no. of available
processors.
public long freeMemory()
returns amount of free memory in
JVM.
public long totalMemory()
returns amount of total memory
in JVM.
49. G
public class Runtime1{
public static void main(String args[])throws Exc
eption{
Runtime.getRuntime().exec("notepad");//will
open a new notepad
}
}
Java Runtime
exec() method
Java Runtime freeMemory() and totalMemory() method
In the given program, after creating 10000
instance, free memory will be less than the
previous free memory. But after gc() call, you
will get more free memory
50. G
public class MemoryTest{
public static void main(String args[])throws Exc
eption{
Runtime r=Runtime.getRuntime();
System.out.println("Total Memory: "+r.totalM
emory());
System.out.println("Free Memory: "+r.freeMe
mory());
for(int i=0;i<10000;i++){
new MemoryTest();
}
System.out.println("After creating 10000 insta
nce, Free Memory: "+r.freeMemory());
System.gc();
System.out.println("After gc(), Free Memory:
"+r.freeMemory());
}
}
Total Memory:
100139008
Free Memory:
99474824
After creating 1000
instance, Free
Memory: 9931055
After gc(), Free
Memory: 1001828
51. G
How to perform
single task by
multiple threads?
If you have to perform single task by many
threads, have only one run() method
class TestMultitasking1 extends Thread{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
TestMultitasking1 t1=new TestMultitasking1();
TestMultitasking1 t2=new TestMultitasking1();
TestMultitasking1 t3=new TestMultitasking1();
t1.start();
t2.start();
t3.start();
}
}
Output :
task one
task one
task one
Note:
Each thread run in a
separate callstack.
53. G
How to
perform
multiple tasks
by multiple
threads
(multitasking
in
multithreading
)?
If you have to perform multiple tasks by
multiple threads , have multiple run() methods
Program of performing two tasks by two threads
class Simple1 extends Thread{
public void run(){
System.out.println("task one");
}
}
class Simple2 extends Thread{
public void run(){
System.out.println("task two");
}
}
class TestMultitasking3{
public static void main(String args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Output :
task one
task two
55. G
What is
synchronization
?
Synchronization in java is the capability
to control the access of multiple threads
to any shared resource.
Java Synchronization is better option
where we want to allow only one thread
to access the shared resource.
Why use
Synchronization
The synchronization is mainly used to
•To prevent thread interference.
•To prevent consistency problem.
There are two types of synchronization
•Process Synchronization
•Thread Synchronization
Types of
Synchronization
56. G
Thread
Synchronization
There are two types of thread
synchronization mutual exclusive and
inter-thread communication.
1.Mutual Exclusive
1.Synchronized method.
2.Synchronized block.
3.static synchronization.
2.Cooperation (Inter-thread
communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from
interfering with one another while sharing
data. This can be done by three ways in java:
•by synchronized method
•by synchronized block
•by static synchronization
57. G
Synchronization is built around an internal
entity known as the lock or monitor. Every
object has an lock associated with it. By
convention, a thread that needs consistent
access to an object's fields has to acquire the
object's lock before accessing them, and then
release the lock when it's done with them.
From Java 5 the package
java.util.concurrent.locks contains several lock
implementations.
Concept of
Lock in Java
58. Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent
Class Table{
void printTable(int n)
{//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){
System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();
//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
Output:
5
100
10
200
15
300
20
400
25
500
59. G
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.
60. class Table{
synchronized void printTable(int n){//synchr
onized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e)
;}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
61. G
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.
Points to remember for Synchronized block
Synchronized block is used to lock an object for
any shared resource.
Scope of synchronized block is smaller than the
method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}
Synchronized
block in java
62. class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e
);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
63. G
If you make any static method as synchronized,
the lock will be on the class not on object.
Static
synchronization
64. G
Suppose there are two objects of a shared
class(e.g. Table) 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.I
want no interference between t1 and t3 or t2
and t4.Static synchronization solves this
problem
Problem
without static
synchronizatio
n
65. class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
1 2 3 4 5 6
9 10 10 20
40 50 60 7
90 100 10
200 300 4
500 600 7
800 900 1
1000 2000
3000 4000
5000 6000
7000 8000
9000 1000
66. G
The block synchronizes on the lock of the
object denoted by the reference .class name
.class.
A static synchronized method printTable(int n)
in class Table is equivalent to the following
declaration:
static void printTable(int n) {
synchronized (Table.class) {
// Synchronized block on class A
// ...
}
}
Synchronized
block on a class
lock
67. G
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 in java
69. G
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()
Inter-thread
communication
in Java
70. G
Method Description
public final void
wait()throws
InterruptedException
waits until object is
notified.
public final void
wait(long
timeout)throws
InterruptedException
waits for the
specified amount of
time.
1) wait() method
Causes current thread to release the lock and
wait until either another thread invokes the
notify() method or the notifyAll() method for
this object, or a specified amount of time has
elapsed.
The current thread must own this object's
monitor, so it must be called from the
synchronized method only otherwise it will
throw exception.
71. G
2) notify() method
Wakes up a single thread that is waiting
on this object's monitor. If any threads
are waiting on this object, one of them is
chosen to be awakened. The choice is
arbitrary and occurs at the discretion of
the implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this
object's monitor. Syntax:
public final void notifyAll()
72. G
Understanding the
process of inter-
thread
communication
The point to point explanation of the above
diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call
wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method,
thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases
the lock and exits the monitor state of the
object.
73. G
Why wait(), notify() and notifyAll() methods are defined in
Object class not Thread class?
It is because they are related to lock and object
has a lock.
wait() sleep()
wait() method releases
the lock
sleep() method doesn't
release the lock.
is the method of Object
class
is the method of
Thread class
is the non-static
method
is the static method
is the non-static
method
is the static method
should be notified by
notify() or notifyAll()
methods
after the specified
amount of time, sleep
is completed.
Difference between wait and sleep?
Let's see the important differences between wait
and sleep methods.
74. class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting fo
r deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output:
going to withdraw...
Less balance; waiting for deposit... going to deposit...
deposit completed...
withdraw completed
75. G
If any thread is in sleeping or waiting state (i.e.
sleep() or wait() is invoked), calling the interrupt()
method on the thread, breaks out the sleeping or
waiting state throwing InterruptedException. If
the thread is not in the sleeping or waiting state,
calling the interrupt() method performs normal
behaviour and doesn't interrupt the thread but
sets the interrupt flag to true. Let's first see the
methods provided by the Thread class for thread
interruption.
Interrupting a
Thread
•public void interrupt()
•public static boolean interrupted()
•public boolean isInterrupted()
The 3 methods provided by the Thread class for
interrupting a thread
76. class TestInterruptingThread1 extends Thre
ad{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interr
upted..."+e);
}
}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterru
ptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exc
eption handled "+e);}
}
}
Output:
Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted at
A.run(A.java:7)
Example of interrupting a thread that stops working
77. G
Reentrant
Monitor in Java
According to Sun Microsystems, Java monitors
are reentrant means java thread can reuse the
same monitor for different synchronized
methods if method is called from the method.
Advantage of Reentrant Monitor
It eliminates the possibility of single thread
deadlocking
Let's understand the java reentrant monitor
by the example given below:
In this class, m and n are the synchronized
methods. The m() method internally calls
the n() method.
class Reentrant {
public synchronized void m() {
n();
System.out.println("this is m() method");
}
public synchronized void n() {
System.out.println("this is n() method");
}
}
78. G
Now let's call the m() method on a thread.
In the class given below, we are creating
thread using annonymous class.
public class ReentrantExample{
public static void main(String args[]){
final ReentrantExample re=new Reentrant
Example();
Thread t1=new Thread(){
public void run(){
re.m();//calling method of Reentrant class
}
};
t1.start();
}}
Output:
this is n() method
this is m() method