Synchronization in Java
Synchronization in Java
• synchronized(sync_object)
•{
• // Access shared variables and other
• // shared resources
•}
Types of Synchronization
Java uses three methods, namely, wait(), notify(), and notifyAll(). All
these methods belong to object class as final so that all classes have
them. They must be used within a synchronized block only.
• wait(): It tells the calling thread to give up the lock and go to sleep
until some other thread enters the same monitor and calls notify().
• notify(): It wakes up one single thread called wait() on the same
object. It should be noted that calling notify() does not give up a lock
on a resource.
• notifyAll(): It wakes up all the threads called wait() on the same
object.
Event Handling in Java
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events :Foreground events are the events that require user interaction to
generate, i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI). Interactions are nothing but clicking on a
button, scrolling the scroll bar, cursor moments, etc.
• Background Events : Events that don’t require interactions of users to generate are
known as background events. Examples of these events are operating system
failures/interrupts, operation completion, etc
Event Handling
It is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows
the Delegation Event model.
Delegation Event model.
• Source: Events are generated from the source. There are various
sources like buttons, checkboxes, list, menu-item, choice, scrollbar,
text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from
the source. Each of these listeners represents interfaces that are
responsible for handling events.
To perform Event Handling, we need to register the source with the
listener.
• Registering the Source With Listener
Syntax: addTypeListener()